手機接收者實作
public class CallPhone
{
private readonly TextBox _tBox;
public CallPhone(MailManager mm, TextBox tBox)
{
_tBox = tBox;
mm.MailMsg += CellPhoneMsg; // 訂閱
}
private void CellPhoneMsg(object sender, MailMsgEventArgs e)
{
_tBox.Text += $"消息到手機:\n來自:{e.from}\n發到:{e.to}\n主題:{e.subject}\n內容:{e.body}\n\n";
}
public void Register(MailManager mm) => mm.MailMsg += CellPhoneMsg;
public void UnRegister(MailManager mm) => mm.MailMsg -= CellPhoneMsg;
}
用戶端表單組裝
public partial class Form1 : Form
{
private Fax _fax;
private CallPhone _cell;
private MailManager _mm;
public Form1()
{
InitializeComponent();
_mm = new MailManager();
_fax = new Fax(_mm, txtReceiver);
_cell = new CallPhone(_mm, txtReceiver);
}
private void btnSend_Click(object sender, EventArgs e)
{
_mm.SimulateArrivingMsg(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
}
private void btnClear_Click(object sender, EventArgs e) => txtReceiver.Clear();
}
關鍵流程
- 表單建立時,將 `MailManager` 注入 `Fax`、`CallPhone` 建構函式
- 接收者在建構函式中訂閱 `MailMsg` 事件
- 使用者點擊發送,呼叫 `SimulateArrivingMsg`
- 管理器建立事件參數,激發 `OnMailMsg`
- 所有訂閱者的處理器依序執行,更新 UI
設計優點
- 單一職責:管理器只管觸發,接收者只管顯示
- 開放封閉:新增 `EmailForwarder`、`SmsGateway` 只需實作處理器並訂閱
- 可測試:可獨立測試管理器觸發邏輯與各接收者格式化邏輯