场景
不同设备对象间通信
实现代码
中介者接口
namespace DesignPatterns.Mediator{ ////// 中介者接口 /// public interface IMediator { ////// 向设备发送消息 /// /// 消息体 /// 设备对象 void Send(string message, IDevice device); }}
中介者实现
namespace DesignPatterns.Mediator{ ////// 中介者 /// public class Mediator : IMediator { ////// Initializes a new instance of the public Mediator() { } ///class. /// /// Gets or sets 设备A对象 /// public DeviceA DeviceA { get; set; } ////// Gets or sets 设备B对象 /// public DeviceB DeviceB { get; set; } ////// 向设备发送数据 /// /// 消息体 /// 设备对象 public void Send(string message, IDevice device) { if (device == this.DeviceA) { this.DeviceB.Notify(message); } else { this.DeviceA.Notify(message); } } }}
设备接口
namespace DesignPatterns.Mediator{ ////// 设备接口 /// public interface IDevice { ////// 接受消息 /// /// 消息体 void Notify(string message); ////// 发送消息 /// /// 消息体 void Send(string message); }}
设备A实现
namespace DesignPatterns.Mediator{ ////// 设备A对象 /// public class DeviceA : IDevice { ////// 中介者对象 /// private Mediator _mediator; ////// Initializes a new instance of the /// 中介者对象 public DeviceA(Mediator mediator) { this._mediator = mediator; } ///class. /// /// 接收消息提示 /// /// 消息 public void Notify(string message) { Console.WriteLine($"Get message in A: {message}"); } ////// 发送消息 /// /// 消息体 public void Send(string message) { this._mediator.Send(message, this); } }}
设备B实现
namespace DesignPatterns.Mediator{ ////// 设备A对象 /// public class DeviceB : IDevice { ////// 中介者对象 /// private Mediator _mediator; ////// Initializes a new instance of the /// 中介者对象 public DeviceB(Mediator mediator) { this._mediator = mediator; } ///class. /// /// 接收消息提示 /// /// 消息 public void Notify(string message) { Console.WriteLine($"Get message in B: {message}"); } ////// 发送消息 /// /// 消息体 public void Send(string message) { this._mediator.Send(message, this); } }}
相关调用
Mediator.Mediator mediator = new Mediator.Mediator();DeviceA deviceA = new DeviceA(mediator);DeviceB deviceB = new DeviceB(mediator);mediator.DeviceA = deviceA;mediator.DeviceB = deviceB;deviceA.Send("发送消息");deviceB.Send("发送消息");
Out:
Get message in B: 发送消息Get message in A: 发送消息