using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; namespace Mediator { //用户接口 public interface IUser { //接收消息 void receiveMessage(String message); //发送消息 void sendMessage(String message); //获得发送的消息内容 string getMessage(); } //中介者接口 public interface IMediator { //注册用户信息 void regist(IUser user); //发送消息给所有人 void notifyAllMessage(IUser user); } public class ConcreteMediator : IMediator { private IList<IUser> list = new List<IUser>(); public void regist(IUser user) { if (user!=null && !list.Contains(user)){ list.Add(user); } } public void notifyAllMessage(IUser user) { for (int i = 0; i < list.Count; i++) { if (!list[i].Equals (user)) { list[i].receiveMessage(user.getMessage()); } } } } //抽象用户信息 public abstract class AbstractUser : IUser { protected IMediator mediator; protected String name; protected String message; public AbstractUser(IMediator mediator, string name) { this.mediator = mediator; this.name = name; } public void sendMessage(String message) { this.message = message; Console.WriteLine(this.name + " 说:" + this.message); mediator.notifyAllMessage(this); } public abstract void receiveMessage(string message); public string getMessage() { return message; } } //用户A public class UserA : AbstractUser { public UserA(IMediator mediator, string name) : base(mediator, name) { mediator.regist(this); } public override void receiveMessage(string message) { Console.WriteLine("User A Received Message :" + message); } } //用户B public class UserB : AbstractUser { public UserB(IMediator mediator, string name) : base(mediator, name) { mediator.regist(this); } public override void receiveMessage(string message) { Console.WriteLine("User B Received Message :" + message); } } //用户C public class UserC : AbstractUser { public UserC(IMediator mediator, string name) : base(mediator, name) { mediator.regist(this); } public override void receiveMessage(string message) { Console.WriteLine("User C Received Message :" + message); } } class Program { static void Main(string[] args) { //创建聊天室(中介者) IMediator mediator = new ConcreteMediator(); //创建用户信息 IUser userA = new UserA(mediator, "张三"); IUser userB = new UserB(mediator, "李四"); IUser userC = new UserC(mediator, "王五"); Console.WriteLine("------------------------------------------------------"); userA.sendMessage("大家好,我叫张三!初来乍到,请多多关照!"); Console.WriteLine(); Console.WriteLine("------------------------------------------------------"); userB.sendMessage("大家好,我叫李四!欢迎加入!"); Console.WriteLine(); Console.WriteLine("------------------------------------------------------"); userC.sendMessage("我是王五,欢迎欢迎!"); Console.WriteLine(); Console.WriteLine("------------------------------------------------------"); } } }
原文地址:http://blog.csdn.net/ry513705618/article/details/39939225