Jas*_*ans 5 command design-patterns
我有一些代码可以更新电子邮件的人员列表.此列表经常更新,在调用代码的实际"发送电子邮件"部分之前添加和删除人员.目前我的代码处理这个是这样的:
if (instructorEmailType == InstructorEmailType.AddToCourse)
{
// If instructor not already in the list, then put them in.
if (!this.InstructorsToEmail.ContainsKey(courseInstructor))
{
this.InstructorsToEmail.Add(courseInstructor, InstructorEmailType.AddToCourse);
}
else
{
// If instructor already in the list, and marked for removal, then get rid
// of that entry from the list.
if (this.InstructorsToEmail[courseInstructor] == InstructorEmailType.RemoveFromCourse)
{
this.InstructorsToEmail.Remove(courseInstructor);
}
}
}
else
{
if (this.InstructorsToEmail.ContainsKey(courseInstructor))
{
this.InstructorsToEmail.Remove(courseInstructor);
}
else
{
this.InstructorsToEmail.Add(courseInstructor, InstructorEmailType.RemoveFromCourse);
}
}
Run Code Online (Sandbox Code Playgroud)
这很复杂,我不喜欢它.我一直在考虑实现Command设计模式.我的想法是创建两个命令:
当教师被分配到课程时,我会新建SendAllocatedInstructorEmailCommand并添加它以CommandInvoker.SetCommand供以后使用.同样,我会SendDeallocatedInstructorEmailCommand为那些退出课程的教师创建一个对象.
那就是问题所在.
如果我已经为该行创建了一个SendAllocatedInstructorEmailCommand对象,Instructor A那么该行Instructor A将从该课程中解除分配(在保存页面上的任何数据或发送电子邮件之前),那么我需要删除SendAllocatedInstructorEmailCommand我之前构建的那个.
什么是搜索已经引用的命令的简洁方法Instructor A,以便我可以删除它们?我不能Undo在我的命令上使用方法,因为电子邮件已经通过SendAllocatedInstructorEmailCommand.
我正在考虑Query为我的CommandInvoker对象添加某种方法,但我不确定这是不是一个糟糕的计划.
我应该使用Command设计模式吗?它确实是一种排队这些电子邮件的好方法.
干杯.雅.
我想说你应该保留你的命令,只是将它们与发送任何电子邮件分离。
您的命令应该类似于IncludeInstructorEmail和ExcludeInstructorEmail,它们都应该实现一个接口,就像这样
public interface ICommandOverEmailsList
{
void ApplyToList(List<string> emailsList);
}
Run Code Online (Sandbox Code Playgroud)
那么主要部分的代码将是这样的:
List<string> emailsList = new List<string>();
foreach(var command in instructorEmailsCommandsQueue)
{
command.ApplyToList(emailsList);
}
SendEmails(emailsList);
Run Code Online (Sandbox Code Playgroud)
当然,这假设像“排除 X,包括 X”这样的命令序列会将地址 X 留在列表中。这看起来和你原来的代码逻辑不一样,但是真的有必要吗?
| 归档时间: |
|
| 查看次数: |
505 次 |
| 最近记录: |