中介模式
来源:互联网 发布:公司域名查询 编辑:程序博客网 时间:2024/04/28 01:16
这个例子讲的是同事之间通过一个中介来收发消息,有一个具体中介类继承抽象中介类,两个具体同事类继承抽象同事类,同事类里面需要有一个中介对象,同时这个中介对象里面需要两种具体同事类(否则不能直接调用子类特有的功能)的对象,每个具体同事对象发送消息时通过中介对象传送到另一个同事对象那去。
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 中介模式{ abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } } abstract class Mediator { public abstract void Send(string message, Colleague colleague); } class ConcreteColleague1 : Colleague { public ConcreteColleague1(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事1得到信息:" + message); } } class ConcreteColleague2 : Colleague { public ConcreteColleague2(Mediator mediator) : base(mediator) { } public void Send(string message) { mediator.Send(message, this); } public void Notify(string message) { Console.WriteLine("同事2得到信息:" + message); } } class ConcreteMediator : Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 Colleague1 { set { colleague1 = value; } } public ConcreteColleague2 Colleague2 { set { colleague2 = value; } } public override void Send(string message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } } class Program { static void Main(string[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("吃过饭了吗?"); c2.Send("没有呢,你打算请客?"); Console.Read(); } }}
同事2得到信息:吃过饭了吗?同事1得到信息:没有呢,你打算请客?
阅读全文
0 0
- 中介模式
- 中介模式
- 中介模式
- 中介模式
- 中介模式
- 设计模式 - 中介模式
- 深入浅出中介者模式
- 中介者(Mediator)模式
- Mediator中介者模式
- 中介者模式
- 中介者模式
- Mediator 中介模式
- Mediator 中介者模式
- 中介者模式Mediator
- 侃中介者模式
- 中介者模式
- 中介者模式 MediatorPattern
- 中介模式的优点
- Linux下配置jdk的方法
- linux线程1
- vs2010+opencv 243 + 摄像头操作
- 【Javascript之】精通JavaScript的this关键字
- 单向链表的操作
- 中介模式
- Gradle错误提示:Java home supplied via 'org.gradle.java.home' is invalid
- FreeMarker模板引擎替代jsp的用法
- codeforces——811B——Vladik and Complicated Book
- SpringMVC返回XML或者JSON格式的数据
- python函数的嵌套调用与嵌套定义
- pycaffe做识别时通道转换问题
- codeblocks--一些东西
- Git的撤销修改及工作区文件删除