概述
中介者模式也是一种行为型的设计模式,其主要的是通过一个中介者代替代对象之间的通信,减少类于类之间的依赖,从而减少代码耦合。中介者模式有几个主要的组成部分,中介者接口,中介者,通信类,当需要通信的时候,通过中介者将具体的信息传到需要传递的类中,实现类于类之间的通信。
例子:在两个城市中,有小明和小红两个笔友,由于距离比较远,两个人没法直接通信,所以需要邮差(中介者)将消息传递给对方,请设计实现。
中介者模式
using static POC;
using System.Numerics;internal class Program
{private static void Main(string[] args){XiaoMing xiaoming = new XiaoMing();XiaoHong xiaohong = new XiaoHong();PostMan PM = new PostMan(xiaoming, xiaohong);//创建中介者xiaohong.Mail();//小红寄出了邮件xiaoming.Mail();//小明寄出了邮件}public interface IMediator{void Notify(IMediator sender, string name);}public class PostMan : IMediator//邮差{private readonly XiaoMing _xiaoming;private readonly XiaoHong _xiaohong;public PostMan(XiaoMing XM, XiaoHong XH){_xiaoming = XM;_xiaohong = XH;_xiaoming.SetMediator(this);_xiaohong.SetMediator(this);}public void Notify(IMediator sender, string name){if (name == "xiaohong"){_xiaohong.Message("通知小红,小明寄出了邮件");}else if (name == "xiaoming"){_xiaoming.Message("通知小明,小红寄出了邮件");}}}public abstract class User//用户基类{protected IMediator _mediator;public void SetMediator(IMediator mediator){_mediator = mediator;}public abstract void Mail();public abstract void Message(string message);}public class XiaoMing : User//用户小明{public override void Mail(){_mediator.Notify(_mediator, "xiaohong");}public override void Message(string message){Console.WriteLine(message);}}public class XiaoHong : User//用户小红{public override void Mail(){_mediator.Notify(_mediator, "xiaoming");}public override void Message(string message){Console.WriteLine(message);}}
}
输出
通知小明,小红寄出了邮件
通知小红,小明寄出了邮件