The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
簡單來說~ 中介者模式封裝一個類(Mediator)~ 將Mediator中的兩個對像進行互動~
換句話說~ Mediator促進兩個對象之間的鬆散~ 並允許使用它來改變它們兩個互動方式~
學習目標: 中介者模式的概念及實務
學習難度: ☆☆☆
using System;
namespace ConsoleApp1
{
public abstract class Mediator //抽象中介者
{
public abstract void Send(string message, Player player); //抽象發送方法(訊息、Player)
}
public class ConcreteMediator : Mediator //實體中介者 (讓兩個對象物件進行交互)
{
ConcretePlayer1 player1; //實體玩家1
ConcretePlayer2 player2; //實體玩家2
public ConcretePlayer1 Player1 //建構實體玩家1
{
set { player1 = value; }
}
public ConcretePlayer2 Player2 //建構實體玩家2
{
set { player2 = value; }
}
public override void Send(string message, Player player) //建構實體發送方法
{
if (player == player1) //當player1傳訊息
{
player2.Notify(message); //player2收到通知
}
else
{
player1.Notify(message); //player1收到通知
}
}
}
public abstract class Player //抽象玩家
{
protected Mediator mediator; //定義中介者
// Constructor
public Player(Mediator mediator) //建構Player,讓Player能有中介者的parameter
{
this.mediator = mediator;
}
}
public class ConcretePlayer1 : Player //實體玩家1
{
//建構實體玩家1,讓它能接受mediator,然後mediator的定義繼承抽象類
public ConcretePlayer1(Mediator mediator) : base(mediator)
{
}
//建構發送訊息的實體方法
public void Send(string message)
{
mediator.Send(message, this); //從中介者送..
}
//建構接收訊息的實體方法
public void Notify(string message)
{
Console.WriteLine("Player1 gets message: " + message);
}
}
public class ConcretePlayer2 : Player //實體玩家2
{
//建構實體玩家2,讓它能接受mediator,然後mediator的定義繼承抽象類
public ConcretePlayer2(Mediator mediator) : base(mediator)
{
}
//建構發送訊息的實體方法
public void Send(string message)
{
mediator.Send(message, this); //從中介者送..
}
//建構接收訊息的實體方法
public void Notify(string message)
{
Console.WriteLine("Player2 gets message: " + message);
}
}
public class MainProgram
{
public static void Main(string[] args)
{
//實體化中介者
ConcreteMediator mediator = new ConcreteMediator();
//實體化player1、player2,並將中介者塞入
ConcretePlayer1 player1 = new ConcretePlayer1(mediator);
ConcretePlayer2 player2 = new ConcretePlayer2(mediator);
mediator.Player1 = player1;
mediator.Player2 = player2;
player1.Send("How are you?");
player2.Send("Fine, thanks");
}
}
}
參考資料:
https://www.dofactory.com/net/mediator-design-pattern