中介者模式

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
IMeditor meditor = new Meditor();
Jack jack = new Jack();
Andre andre = new Andre();
meditor.Register(jack);
meditor.Register(andre);
jack.SendMessage("test","你好\n");
jack.SendMessage("andre", "你好\n");
Console.ReadKey();
}
public interface IMeditor {
void Register(IChatRoomPerson chatRoomPerson);
void Send(string from, string to, string message);
}
public class Meditor : IMeditor
{
List<IChatRoomPerson> _listChatRoomPerson = new List<IChatRoomPerson>();
public void Register(IChatRoomPerson chatRoomPerson)
{
IChatRoomPerson oldChatRoomPerson = _listChatRoomPerson.Where(l => l.Name == chatRoomPerson.Name).FirstOrDefault();
if (oldChatRoomPerson == null) {
_listChatRoomPerson.Add(chatRoomPerson);
chatRoomPerson.Meditor = this;
}
}
public void Send(string from, string to, string message)
{
IChatRoomPerson chatRoomPerson= _listChatRoomPerson.Where(l=>l.Name==to).FirstOrDefault();
if (chatRoomPerson != null)
{
chatRoomPerson.ReceiveMessage(from, message);
}
else {
Console.WriteLine("该聊天室没有此人注册\n");
}
}
}
public interface IChatRoomPerson {
string Name { get; }
IMeditor Meditor { get; set; }
void SendMessage(string to,string message);
void ReceiveMessage(string from,string message );
}
public class ChatRoomPerson : IChatRoomPerson
{
private string _name;
private IMeditor _meditor;
public ChatRoomPerson(string name) {
_name = name;
}
public void SendMessage(string to, string message)
{
Console.Write($"我发送给{to}一条消息,内容:{message}\n");
_meditor.Send(_name, to,message);
}
public void ReceiveMessage(string from, string message)
{
Console.Write($"我从{from}获得一条消息,内容:{message}\n");
}
public string Name { get { return _name; } }

public IMeditor Meditor{get{ return _meditor;}set{ _meditor = value;}}
}
public class Andre : ChatRoomPerson
{
public Andre() : base("andre")
{
}
}
public class Jack : ChatRoomPerson
{
public Jack() : base("jack")
{
}
}
}
}

posted @ 2019-03-22 09:33  东东东  阅读(63)  评论(0)    收藏  举报