行为设计模式之一,允许对象在中介者的帮助下相互通信。
中介器通过防止对象相互直接依赖来促进松散耦合。相反,他们使用中介来相互沟通。
让我们通过实现不同用户互相聊天的聊天室来理解这一点
调解员
public interface chatmediator { public void sendmessage(user user, string message); public void adduser(user user); } public class chatroommediator implements chatmediator { private list<user> users; public chatroommediator(){ this.users = new arraylist(); } @override public void adduser(user u){ users.add(u); } @override public void sendmessage(user u, string message){ for(user user : users){ if(user!=u){ user.receive(message); } } } } </user>
用户
public class user { chatmediator mediator; private string name; public user(string n,chatmediator m){ this.name = n; this.mediator = m; } public string getname(){ return this.name; } public void send(string message){ system.out.println(this.name+":sent:"+message); mediator.sendmessage(this,message); } public void receive(string message){ system.out.println(this.name+":received:"+ message); } }
主要
public class main { public static void main(string args[]){ chatmediator mediator = new chatroommediator(); user user1 = new user("prashant",mediator); user user2 = new user("sandeep", mediator); user user3 = new user("ajay", mediator); mediator.adduser(user3); mediator.adduser(user2); mediator.adduser(user1); user1.send("hi all"); user2.send("hi prashant"); user3.send("hi..."); } }
输出:
prashant:sent:Hi All ajay:received:Hi All sandeep:received:Hi All sandeep:sent:Hi Prashant ajay:received:Hi Prashant prashant:received:Hi Prashant ajay:sent:Hi... sandeep:received:Hi... prashant:received:Hi...
要点
- 用户对象松散耦合,即即使某些用户被删除或修改也不会影响任何其他用户
- mediator 是所有用户之间的中间人
以上就是调解员的详细内容,更多请关注php中文网其它相关文章!
版权声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系 yyfuon@163.com