一,什么是中介者模式(Mediator Pattern)?
中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。比如:如果我们实现两个人的交互,难道我们要定义两个对象如ChineseA,ChineseB和ChineseC,然后他们都一起说话聊天,我们要他们之间的交互改成他们和中介的交互实现聊天。在这里我们需要用到中介者设计模式,将交互的由将交互的形式有对象-对象转变为,对象-中介-对象的形式
二,如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _17.中介者模式
{
//中介者模式适合用于多个对象之间紧密耦合的情况,紧密耦合的标准是:在类图中出现了蜘蛛网状结构。这有利于把蜘蛛网状结构梳理为星型结构,
//使原本复杂混乱的关系变得清晰简单
//用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立的改变它们之间的交互。
//比如:如果我们实现两个人的交互,难道我们要定义两个对象如ChineseA,ChineseB和ChineseC,然后他们都一起说话聊天,
//我们要他们之间的交互改成他们和中介的交互实现聊天。在这里我们需要用到中介者设计模式,将交互的将交互的形式有对象-对象转变为,对象-中介-对象的形式
class Program
{
static void Main(string[] args)
{
People chinese1 = new Chinese()
{
Name = "中国人1"
}; People chinese2 = new Chinese()
{
Name = "中国人2"
}; People usa = new Usa()
{
Name = "美国人"
}; ////初始化要传递给谁的数据
Mediator mediator = new Mediator();
mediator.Addpeople(chinese1);
mediator.Addpeople(usa); ////中国人发送消息
mediator.SendMessage("聚餐啦啦啦啦!!", chinese2);
}
}
/// <summary>
/// 抽象类
/// </summary>
public abstract class People
{
public string Name { get; set; }
public abstract void SendMessage(string message, People peopleTo);
public abstract void GetMessage(string message, People peopleFrom);
}
/// <summary>
/// 中国人,具体实现类
/// </summary>
public class Chinese : People
{
public override void SendMessage(string message, People peopleTo)
{
Console.WriteLine("{0}说 {1}:{2}", base.Name, peopleTo.Name, message);
peopleTo.GetMessage(message, this);
} public override void GetMessage(string message, People peopleFrom)
{
Console.WriteLine("{0}get{1}:{2}", base.Name, peopleFrom.Name, message);
}
}
/// <summary>
/// 美国人,具体实现类
/// </summary>
public class Usa : People
{
public override void SendMessage(string message, People peopleTo)
{
Console.WriteLine("{0}说 {1}:{2}", base.Name, peopleTo.Name, message); peopleTo.GetMessage(message, this); } public override void GetMessage(string message, People peopleFrom)
{
Console.WriteLine("{0}get{1}:{2}", base.Name, peopleFrom.Name, message);
}
}
/// <summary>
/// 中介类
/// 比如一个通信平台,本来是中国人通知美国人的,现在是一个中介者通知所有人,解耦合
/// </summary>
public class Mediator
{
public string Name { get; set; }
private List<People> _peopleList = new List<People>(); public void Addpeople(People basepeople)
{
this._peopleList.Add(basepeople);
} /// <summary>
/// 群里面发消息的功能
/// </summary>
/// <param name="message"></param>
/// <param name="peopleFrom"></param>
public void SendMessage(string message, People peopleFrom)
{
Console.WriteLine("{0}Send:{1}", peopleFrom.Name, message);
foreach (var item in this._peopleList)
{
item.GetMessage(message, peopleFrom);
}
}
}
}