设计模式C#实现(十六)——中介者模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式C#实现(十六)——中介者模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
-
- 意圖
- 適用性
- 結構
- 實現
- 效果
- 參考
?
意圖
用一個中介對象來封裝一系列的對象交互。中介者使各對象不需要顯示地相互引用,從而使其耦合松散,而且可以獨立地改變他們之間的交互。
適用性
- 一組對象以定義良好但是復雜的方式進行通信。產生的相互依賴關系結構混亂且難以理解。
- 一個對象引用其他很多對象并且之間
- 想定制一個分布在多個類中的行為,而又不想生成太多子類。
結構
實現
在未來的智能家居中,家里的各種電器相互關聯,假設這樣三種電器:鬧鐘,日歷和咖啡壺。現在有這樣兩個任務:
同事類,每一個同事都知道他的中介者,當它需要與其他同事交流時,它只需通知中介者。
public abstract class Colleague{protected string _type;protected Mediator _theMediator;public string Type{get { return _type; }}public Mediator TheMediator{get { return _theMediator; }set { _theMediator = value; }}}具體同事
public class Alarm : Colleague{public Alarm(){_type = "Alarm";}public void AlarmLater(){Console.WriteLine("Alarm 5min later");_theMediator.Notify(this);}public void PowerOff(){Console.WriteLine("Alarm PowerOff");}}public class CoffeePot : Colleague{public CoffeePot(){_type = "CoffeePot";}public void PrepareCoffee(){Console.WriteLine("Start preparing coffee");}public void PowerOff(){Console.WriteLine("CoffeePot PowerOff");}}public class Calendar : Colleague{public Calendar(){_type = "Calendar";}public DayOfWeek GetDayOfWeek(){return DateTime.Today.DayOfWeek;}public void PowerOff(){Console.WriteLine("Calendar PowerOff");_theMediator.Notify(this);}}中介者定義一個用于與各同事通信的接口
public class Mediator{public virtual void Notify(Colleague colleague){}}具體中介者了解和維護各個同事,并協調各同事以實現協作行為。
public class FutureHouse : Mediator{private Alarm _alarm;private CoffeePot _coffeePot;private Calendar _calendar;public Calendar HouseCalendar{get { return _calendar; }set { _calendar = value; }}public CoffeePot HouseCoffeePot{get { return _coffeePot; }set { _coffeePot = value; }}public Alarm HouseAlarm{get { return _alarm; }set { _alarm = value; }}private void WeekUp(){if (HouseCalendar.GetDayOfWeek()!=DayOfWeek.Sunday){HouseCoffeePot.PrepareCoffee();}}private void PowerOff(){HouseCoffeePot.PowerOff();HouseAlarm.PowerOff();}public override void Notify(Colleague colleague){if (colleague.Type == "Alarm"){WeekUp();}else if (colleague.Type == "Calendar"){PowerOff();}}}使用
class Program{static void Main(string[] args){var calendar = new Calendar();var coffeePot = new CoffeePot();var alarm = new Alarm();var house = new FutureHouse();calendar.TheMediator = house;alarm.TheMediator = house;coffeePot.TheMediator = house;house.HouseCalendar = calendar;house.HouseAlarm = alarm;house.HouseCoffeePot = coffeePot;alarm.AlarmLater();calendar.PowerOff();Console.ReadKey();}}運行結果
- 周日
- 非周日
效果
參考
轉載于:https://www.cnblogs.com/castdream/p/5137462.html
總結
以上是生活随笔為你收集整理的设计模式C#实现(十六)——中介者模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Entity Framework 6 R
- 下一篇: 分享:一个基于NPOI的excel导入导