public ActionResult Notify() { 傳送訊息DemoControl control = new 傳送訊息DemoControl(); // new a control object. NotifyType notifytype; // declare enumernation type reference. SenderType sendertype; Message message = new Message(); // Data Transfer Object. // 判斷選擇哪一種通知類型 if (Request.Form["NotifyType"].Equals("SystemNotify")) notifytype = NotifyType.System; else notifytype = NotifyType.User; // 判斷選擇哪一種傳送方式 if (Request.Form["SenderType"].Equals("EmailSender")) sendertype = SenderType.Email; else sendertype = SenderType.Line; // 組裝 Message 物件的內容 message.Recipient = Request.Form["txtRecipient"]; message.Subject = Request.Form["txtSubject"]; message.Body = Request.Form["txtBody"]; // 交由 control 委派處理 string procResult = control.Notify(notifytype, sendertype, message); ViewData["result"] = procResult; return View(); }
/// <summary> /// 處理傳遞訊息的控制邏輯 /// </summary> /// <param name="notifytype">enum: System, User</param> /// <param name="sendertype">enum: Email, Line</param> /// <param name="message">訊息物件</param> /// <returns></returns> public string Notify(NotifyType notifytype, SenderType sendertype, Message message) { string procResult = ""; // 判斷需產出哪一個 RefinedAbstraction 的子類別物件 switch (notifytype) { case NotifyType.System : notifier = new SystemNotifier(); break; case NotifyType.User : notifier = new UserNotifier(); break; } // 判斷需哪個實作 MessageSender 介面的實作物件來服務 // 實務上會設計如 List or Hastable 集合儲存這些實作物件,並透過 Key 來取得相對應的實作物件 switch (sendertype) { case SenderType.Email : notifier.sender = mailSender; break; case SenderType.Line : notifier.sender = lineSender; break; } // 回傳執行結果,藉此觀察使用哪一個 Notifier 子類別物件與 MessengSender 物件 procResult = notifier.Notify(message); return procResult; }
// 實務上,需實作呼叫 Line 系統的 API // 將訊息傳入至 Line 系統 public string SendMessage(Message msg) { string result; result = "交由 Line Sender 傳送:\n\n" + "收件人:" + msg.Recipient + "\n" + "主旨 :" + msg.Subject + "\n" + "內容 :" + msg.Body; return result; }
/// <summary> /// 實現 Notify 處理的程序 /// </summary> /// <param name="message">Message 物件</param> /// <returns>處理結果</returns> public override string Notify(Message message) { string procResult; // 處理結果 // 1. 將訊息傳送給所指定的收件人 procResult = sender.SendMessage(message); return procResult; }
/// <summary> /// 實現 Notify 處理的程序 /// </summary> /// <param name="message">Message 物件</param> /// <returns>處理結果</returns> public override string Notify(Message message) { string procResult; // 處理結果 // 1. 寫入到 System Event Log procResult = "程序:訊息內容寫入到 System Event Log\n\n"; // 2.1 將訊息內容編碼 procResult = procResult + "執行編碼程序:\n"; message.Body = sender.編碼(message.Body); // 2.2 將訊息傳送給所指定的收件人 procResult = procResult + sender.SendMessage(message); return procResult; }
// 定義為抽象方法,交由子類別來實作 public abstract string Notify(Message message);