[設計模式練習]仲介者模式
研發部門跟操作部門利用仲介者來溝通訊息及產生回應動作
類別圖
物件檔定義
using System.Collections.Generic;
using System.Text;
namespace DesignModelTest.仲介者
{
/// <summary>
/// Mediator類別: IT管理部門
/// </summary>
abstract class ITManager
{
public abstract void Action(string message, ITDepartment itdepartment);
}
/// <summary>
/// Colleague類別:IT部門
/// </summary>
abstract class ITDepartment
{
protected ITManager mediator;
/// <summary>
/// 加入仲介者監控訊息交換.
/// </summary>
/// <param name="mediator">The mediator.</param>
public ITDepartment(ITManager mediator)
{
this.mediator = mediator;
}
}
/// <summary>
/// ConcreteColleague類別:研發部門
/// </summary>
class RDDepartment : ITDepartment
{
public RDDepartment(ITManager mediator) : base(mediator) { }
public void Action(string message)
{
//將動作經由仲介者傳遞
mediator.Action(message,this);
}
public void GetMessage(string message)
{
//取得對方資訊
Console.WriteLine("研發部門獲得資訊:" + message);
}
}
/// <summary>
/// ConcreteColleague類別:操作部門
/// </summary>
class OPDepartment : ITDepartment
{
public OPDepartment(ITManager mediator) : base(mediator) { }
public void Action(string message)
{
mediator.Action(message, this);
}
public void GetMessage(string message)
{
Console.WriteLine("操作部門獲得資訊:" + message);
}
}
/// <summary>
/// ConcreteMediator類別: IT社群
/// </summary>
class ITSociety : ITManager
{
//所有的ConcreteColleague類別都要加入
private RDDepartment _rd;
private OPDepartment _op;
public RDDepartment rd
{
set { _rd = value; }
}
public OPDepartment op
{
set { _op = value; }
}
//訊息交換(包括邏輯判斷)
public override void Action(string message, ITDepartment itdepartment)
{
if (itdepartment == _rd)
{
_op.GetMessage(message);
}
else
{
_rd.GetMessage(message);
}
}
}
}
用戶端程式碼
DesignModelTest.仲介者.ITSociety itgroup = new DesignModelTest.仲介者.ITSociety();
//讓ConcreteColleague類別認識仲介者
DesignModelTest.仲介者.OPDepartment op = new DesignModelTest.仲介者.OPDepartment(itgroup);
DesignModelTest.仲介者.RDDepartment rd = new DesignModelTest.仲介者.RDDepartment(itgroup);
//讓仲介者認識ConcreteColleague類別
itgroup.op = op;
itgroup.rd = rd;
//發送訊息都透過仲介者發送
rd.Action("要求換版");
op.Action("換版完畢");
Console.Read();
#endregion
輸出結果