多人参加的聊天室,聊天室类和参加者类之间的关系也是Mediator设计模式,参加者注册进聊天室,通过聊天室发送和接受消息,各个聊天参加者才能顺利的聊天。这个例子用Mediator设计模式实现如下:
/// Mediator 设计模式
class MainApp
{
static void Main()
{
//创建聊天室
Chatroom chatroom = new Chatroom();
//创建聊天室的参加者对象
Participant George = new Beatle("George");
Participant Paul = new Beatle("Paul");
Participant Ringo = new Beatle("Ringo");
Participant John = new Beatle("John");
//参加者进入聊天室
chatroom.Register(George);
chatroom.Register(Paul);
chatroom.Register(Ringo);
chatroom.Register(John);
//聊天室作为中间人,参加者向聊天对象发送消息。
Paul.Send("Ringo", "All you need is love");
Ringo.Send("George", "My sweet Lord");
Paul.Send("John", "Can't buy me love");
Paul.Send("Yoko", "Are you there?");
// Wait for user
Console.ReadKey();
}
}
//聊天室的抽象类,包含一个注册接口,发送消息接口。
abstract class AbstractChatroom
{
public abstract void Register(Participant participant);
public abstract void Send(string from, string to, string message);
}
//聊天室类
class Chatroom : AbstractChatroom
{
//加入聊天室的聊天者列
private Dictionary_participants =
new Dictionary();
//聊天者加入该聊天室。
public override void Register(Participant participant)
{
if (!_participants.ContainsValue(participant))
{
_participants[participant.Name] = participant;
}
participant.Chatroom = this;
}
//通过聊天室,将发送者的消息传送给接收者
public override void Send(
string from, string to, string message)
{
if (_participants.ContainsKey(to))
{
Participant participant = _participants[to];
if (participant != null)
{
participant.Receive(from, message);
}
}//如果接收者没有注册进聊天室,则系统提示。
else
{
Console.Write("From System: Cannot send a {0} (not exist)",to);
}
}
}
//聊天室参加者的抽象类
class Participant
{
private Chatroom _chatroom;
private string _name;
// Constructor
public Participant(string name)
{
this._name = name;
}
// Gets participant name
public string Name
{
get { return _name; }
}
// Gets chatroom
public Chatroom Chatroom
{
set { _chatroom = value; }
get { return _chatroom; }
}
// Sends message to given participant
public void Send(string to, string message)
{
_chatroom.Send(_name, to, message);
}
// Receives message from given participant
public virtual void Receive(
string from, string message)
{
Console.WriteLine("{0} to {1}: '{2}'", from, Name, message);
}
}
//聊天室参加者类
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);
}
}
执行结果:
To a Beatle: Paul to Ringo: 'All you need is love'
To a Beatle: Ringo to George: 'My sweet Lord'
To a Beatle: Paul to John: 'Can't buy me love'
From System: Cannot send a Yoko (not exist)
没有评论:
发表评论