2010-10-25 52 views
5

我有一些更新電子郵件的人列表的代碼。此列表經常更新,人們在調用代碼的實際「發送電子郵件」部分之前被添加和刪除。目前我的代碼照顧這是這樣的:關於使用命令設計模式的思考

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); 
    } 
} 

這很複雜,我不喜歡它。我一直在考慮實施Command設計模式。我的想法是什麼,以創建兩個命令:

  • SendAllocatedInstructorEmailCommand
  • SendDeallocatedInstructorEmailCommand

當教師被分配到一門課程,那我就新了SendAllocatedInstructorEmailCommand並將其添加到CommandInvoker.SetCommand供以後使用。同樣,我會爲那些脫下課程的導師創建一個對象。

這就是問題所在。

如果我創建了一個SendAllocatedInstructorEmailCommand對象Instructor A,後來下了線Instructor A從課程(前網頁上的任何數據已保存,或發送的電子郵件)釋放,那麼我需要刪除SendAllocatedInstructorEmailCommand我早先建造。

什麼是搜索已經引用Instructor A的命令的乾淨方式,以便我可以刪除它們?我的命令不能使用Undo方法,因爲電子郵件已經通過SendAllocatedInstructorEmailCommand發送。

我正在考慮爲我的CommandInvoker對象添加某種Query方法,但我不確定這是否是一個糟糕的計劃。

我應該使用Command設計模式嗎?它確實是將這些電子郵件排隊的一種非常好的方式。

乾杯。 Jas。

+0

我不確定我關注。爲什麼你需要刪除'SendAllocatedInstructorEmailCommand'?它是否與已經提及「教練A」的詢問獨立無關? – 2010-10-30 17:29:47

回答

1

我想說,你應該保持你的命令,只是解除他們發送任何電子郵件。

你的命令應該是像IncludeInstructorEmailExcludeInstructorEmail,他們都應該實現一個接口,這樣

public interface ICommandOverEmailsList 
{ 
    void ApplyToList(List<string> emailsList); 
} 

然後在主體部分的代碼會是這樣:

List<string> emailsList = new List<string>(); 
foreach(var command in instructorEmailsCommandsQueue) 
{ 
    command.ApplyToList(emailsList); 
} 
SendEmails(emailsList); 

當然,這假設像「排除X,包含X」這樣的命令序列將地址X留在列表中。這似乎與您的原始代碼邏輯有所不同,但它真的需要嗎?