using
System;
using
System.Linq;
using
System.Text;
namespace
DesignPatterns.Mediator
{
abstract
class
AbstractChatroom
{
public
abstract
void
Register(Participant participant);
public
abstract
void
Send(string from, string to, string message);
}
class
Chatroom : AbstractChatroom
{
private
System.Collections.Hashtable participants =
new
System.Collections.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);
}
}
}
class
Participant
{
private
Chatroom chatroom;
private
string name;
public
Participant(string name)
{
this
.name = name;
}
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)
{
Console.WriteLine(
"{0} to {1}:'{2}'"
, from, name, message);
}
}
class
Beatle : Participant
{
public
Beatle(string name)
: base(name)
{ }
public
override
void
Receive(string from, string message)
{
Console.Write(
"To a Beatle: "
);
base.Receive(from, message);
}
}
class
NonBeatle : Participant
{
public
NonBeatle(string name)
: base(name)
{ }
public
override
void
Receive(string from, string message)
{
Console.Write(
"To a non-Beatle:"
);
base.Receive(from, message);
}
}
class
Program
{
static
void
Main(string[] args)
{
Chatroom chatroom =
new
Chatroom();
Participant George =
new
Beatle(
"George"
);
Participant Paul =
new
Beatle(
"Paul"
);
Participant Ringo =
new
Beatle(
"Ringo"
);
Participant John =
new
NonBeatle(
"John"
);
Participant Yoko =
new
NonBeatle(
"Yoko"
);
chatroom.Register(George);
chatroom.Register(Paul);
chatroom.Register(Ringo);
chatroom.Register(John);
chatroom.Register(Yoko);
George.Send(
"Yoko"
,
"你说错话了"
);
Yoko.Send(
"George"
,
"哪里说错了?"
);
Console.ReadKey();
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
· 聊一聊 操作系统蓝屏 c0000102 的故障分析
· SQL Server 内存占用高分析
· 盘点!HelloGitHub 年度热门开源项目
· DeepSeek V3 两周使用总结
· 02现代计算机视觉入门之:什么是视频
· C#使用yield关键字提升迭代性能与效率
· 2. 什么?你想跨数据库关联查询?
2010-10-14 Ubuntu下可用的IM客戶端