背景
示例
using static System.Console;
namespace DesignPattern_Mediator
{
using static System.Console;
namespace DesignPattern_Mediator
{
// 成员接口
public interface IMemeber
{
void Send(IMemeber to, string message);
void Recieve(IMemeber fm, string message);
}
// 成员类
public class Member : IMemeber
{
private readonly string name;
private readonly ChatRoom room;
public Member(string name, ChatRoom room)
{
this.name = name;
this.room = room;
}
// 通过中介联络
public void Send(IMemeber to, string message)
=> room.Send(this, to, message);
public void Recieve(IMemeber fm, string message)
=> WriteLine($"{fm} to {this}: {message}");
public override string ToString() => name;
}
// 中介者接口
public interface IChatRomm
{
void Send(IMemeber fm, IMemeber to, string message);
}
// 中介者类
public class ChatRoom : IChatRomm
{
public ChatRoom() { }
public void Send(IMemeber fm, IMemeber to, string message)
{
to.Recieve(fm, message);
}
}
class Program
{
static void Main(string[] args)
{
var room = new ChatRoom();
var zhang = new Member("Zhang", room);
var li = new Member("Li", room);
zhang.Send(li, "Hello");
li.Send(zhang, "Hi");
ReadKey();
}
}
}
网友评论