前言
中介者模式:是两者之间通过第三者来帮助传话。
代码
csharp
//抽象接收者
public abstract class Receiver
{
protected Mediator mediator;
protected Receiver(Mediator mediator)
{
this.mediator = mediator;
}
public abstract void SendMessage(string message);
public abstract void ReceiveMessage(string message);
}
//具体接收者A
public class ReceiverA : Receiver
{
public ReceiverA(Mediator mediator) : base(mediator){}
public override void ReceiveMessage(string message)
{
Console.WriteLine($"{this.GetType().Name} got a message[{message}]");
}
public override void SendMessage(string message)
{
Console.WriteLine($"{this.GetType().Name}:a message was send...");
mediator.SendMessage(this,message);
}
}
//具体接收者B
public class ReceiverB : Receiver
{
public ReceiverB(Mediator mediator) : base(mediator) { }
public override void ReceiveMessage(string message)
{
Console.WriteLine($"{this.GetType().Name} got a message[{message}]");
}
public override void SendMessage(string message)
{
Console.WriteLine($"{this.GetType().Name}:a message was send...");
mediator.SendMessage(this, message);
}
}
//中介接口
public interface Mediator
{
void SendMessage(Receiver obj, string message);
}
//具体中介者类
public class ReceiveMediator : Mediator
{
private Receiver receiverA;
private Receiver receiverB;
public void SetReceiveA(Receiver receiverA)
{
this.receiverA = receiverA;
}
public void SetReceiveB(Receiver receiverB)
{
this.receiverB = receiverB;
}
public void SendMessage(Receiver receiver, string message)
{
if(receiver == receiverA)
{
receiverB.ReceiveMessage(message);
}else if(receiver == receiverB)
{
receiverA.ReceiveMessage(message);
}
}
}
/*
* 行为型模式:Behavioral Pattern
* 中介者模式:Mediator Pattern
*/
internal class Program
{
static void Main(string[] args)
{
ReceiveMediator receiveMediator = new ReceiveMediator();
ReceiverA receiverA = new ReceiverA(receiveMediator);
ReceiverB receiverB = new ReceiverB(receiveMediator);
receiveMediator.SetReceiveA(receiverA);
receiveMediator.SetReceiveB(receiverB);
receiveMediator.SendMessage(receiverA, "Hello receiverB");
receiveMediator.SendMessage(receiverB, "Hello receiverA");
Console.ReadLine();
}
}