首页 > 代码库 > Mediator模式
Mediator模式
参考资料《大话设计模式》
Mediator(中介者)模式:
使各个对象不需要显式的相互调用,从而使其耦合松散。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ds_mediator { class Program { static void Main(string[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleage1 c1 = new ConcreteColleage1(m); ConcreteColleage2 c2 = new ConcreteColleage2(m); m.colleage1 = c1; m.colleage2 = c2; c1.Send("你好!"); c2.Send("谢谢!"); } } //抽象同事类 abstract class Colleage { protected Mediator mediator; public Colleage(Mediator mediator) { this.mediator = mediator;//得到中介者对象 } } class ConcreteColleage1 : Colleage { public ConcreteColleage1(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事1得到消息:" + message); } } class ConcreteColleage2 : Colleage { public ConcreteColleage2(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事2得到消息:" + message); } } //抽象中介者 abstract class Mediator { public abstract void Send(string message, Colleage collgeage); } class ConcreteMediator : Mediator { public ConcreteColleage1 colleage1; public ConcreteColleage2 colleage2; public override void Send(string message, Colleage colleage) { if (colleage == colleage1) { colleage2.Notify(message); } else { colleage1.Notify(message); } } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。