📄 class1.cs
字号:
using System;
using System.Collections;
//中介者接口
interface IChatroom
{
void Register( Participant participant );
void Send( string from, string to, string message );
}
//具体中介者-聊天室类
class Chatroom : IChatroom
{
//参与者
private Hashtable participants = new Hashtable();
//先注册参与者
public void Register( Participant participant )
{
if( participants[ participant.Name ] == null )
participants[ participant.Name ] = participant;
participant.Chatroom = this;
}
//发送信息
public 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 );
}
//虚拟接收函数
virtual public void Receive(
string from, string message )
{
Console.WriteLine( "{0} to {1}: '{2}'",
from, this.name, message );
}
}
//具体同事类-Beatle参与者(有个乐队组合叫Beatles)
class BeatleParticipant : Participant
{
// Constructors
public BeatleParticipant( string name )
: base ( name ) { }
override public void Receive(
string from, string message )
{
Console.Write( "To a Beatle: " );
base.Receive( from, message );
}
}
//具体同事类-非Beatle参与者
class NonBeatleParticipant : Participant
{
//调用基类的构造函数
public NonBeatleParticipant( string name )
: base ( name ) { }
override public void Receive(
string from, string message )
{
Console.Write( "To a non-Beatle: " );
base.Receive( from, message );
}
}
/// <summary>
/// 中介者模式测试程序
/// </summary>
public class MediatorApp
{
public static void Main(string[] args)
{
//创建聊天室
Chatroom c = new Chatroom();
//创造参与者及登记入聊天室
Participant George = new BeatleParticipant("George");
Participant Paul = new BeatleParticipant("Paul");
Participant Ringo = new BeatleParticipant("Ringo");
Participant John = new BeatleParticipant("John") ;
Participant Yoko = new NonBeatleParticipant("Yoko");
c.Register( George );
c.Register( Paul );
c.Register( Ringo );
c.Register( John );
c.Register( Yoko );
//成员间聊天
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" ) ;
Console.Read();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -