场景: 假设正在为stackoverflow开发一个新功能,该功能会在一个问题获得10个赞时向其所有者发送电子邮件通知。 领域对象模型如下所示:
public class Question
{
string Question { get; set; }
IList<Votes> Upvotes { get; set; }
User Owner { get; set; }
public void AddUpvote(Vote upvote)
{
Upvotes.Add(upvote);
}
}
潜在的实现方式:
Change
AddUpvote()
to take anIEmailerService
parameter and perform the logic within theAddUpvote()
method.public void AddUpvote(Vote upvote, IEmailerService emailer) { Upvotes.Add(upvote); if ( Upvotes.Count == 10 ) { emailer.Send(Owner.EmailAddr); } }
Detect this state within
AddUpvote()
and haveAddUpvote()
resolve an IEmailService from an IoC container (instead of passing the IEmailerService as a parameter).Detect this state in the external service object that invokes
question.AddUpvote()
.public void UpvoteClickHandler(Question question) { question.AddUpvote(new Upvote()); if ( question.Upvotes.Count == 10 ) { _emailer.Send(question.Owner.EmailAddr); } }
Your better solution here!