?? mediatorrealworld.cs
字號:
using System;
using System.Windows.Forms;
using System.Collections;
//中介者模式(Mediator)
//意圖
// 用一個中介對象來封裝一系列的對象交互。中介者使各對象不需要顯式地相互引用,從而使其耦合松散,而且可以獨立地改變它們之間的交互。
//適用性
// 1.一組對象以定義良好但是復雜的方式進行通信。產生的相互依賴關系結構混亂且難以理解。
// 2.一個對象引用其他很多對象并且直接與這些對象通信,導致難以復用該對象。
// 3.想定制一個分布在多個類中的行為,而又不想生成太多的子類。
namespace DesignPattern.MediatorRealWorld
{
class MediatorRealWorld : AbstractPattern
{
public static void Run(TextBox tbInfo)
{
s_tbInfo = tbInfo;
s_tbInfo.Text = "";
// Create chatroom
Chatroom chatroom = new Chatroom();
//Create participants and register them
Participant George = new Beatle("George");
Participant Paul = new Beatle("Paul");
Participant Ringo = new Beatle("Ringo");
Participant John = new Beatle("John") ;
Participant Yoko = new NonBeatle("Yoko");
chatroom.Register(George);
chatroom.Register(Paul);
chatroom.Register(Ringo);
chatroom.Register(John);
chatroom.Register(Yoko);
// Chatting participants
Yoko.Send ("John", "Hi John!");
Paul.Send ("Ringo", "All you need is love");
Ringo.Send("George", "My sweet Lord");
Paul.Send ("John", "Can't buy me love");
John.Send ("Yoko", "My sweet love") ;
// Wait for user
//Console.Read();
}
}
// "Mediator"
abstract class AbstractChatroom
{
public abstract void Register(Participant participant);
public abstract void Send( string from, string to, string message);
}
// "ConcreteMediator"
class Chatroom : AbstractChatroom
{
private Hashtable participants = new Hashtable();
public override void Register(Participant participant)
{
if (participants[participant.Name] == null)
{
participants[participant.Name] = participant;
}
participant.Chatroom = this;
}
public override void Send(string from, string to, string message)
{
Participant pto = (Participant)participants[to];
if (pto != null)
{
pto.Receive(from, message);
}
}
}
// "AbstractColleague"
class Participant
{
private Chatroom chatroom;
private string name;
// Constructor
public Participant(string name)
{
this.name = name;
}
// Properties
public string Name
{
get{ return name; }
}
public Chatroom Chatroom
{
set{ chatroom = value; }
get{ return chatroom; }
}
public void Send(string to, string message)
{
chatroom.Send(name, to, message);
}
public virtual void Receive(string from, string message)
{
DesignPattern.FormMain.OutputInfo("{0} to {1}: '{2}'", from, Name, message);
}
}
//" ConcreteColleague1"
class Beatle : Participant
{
// Constructor
public Beatle(string name) : base(name)
{
}
public override void Receive(string from, string message)
{
Console.Write("To a Beatle: ");
base.Receive(from, message);
}
}
//" ConcreteColleague2"
class NonBeatle : Participant
{
// Constructor
public NonBeatle(string name) : base(name)
{
}
public override void Receive(string from, string message)
{
Console.Write("To a non-Beatle: ");
base.Receive(from, message);
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -