原文链接:http://www.hechunchen.info/?p=54
生活中的中介者非常常见,比如维护世界和平的联合国组织、房屋中介、出国中介。那么,设计模式中的中介者模式是怎么样的呢?我们openfire中的群组聊天就是a typical example。我们用一个简化的群组聊天模型来说明mediator(中介者)模式。
我们的考虑是这样的,我们在用户之间添加中介者——聊天室。这样的话,用户之间的耦合度就会降低,而且不需要相互引用。它们只需独立地跟中介者交互即可。 结构图如下:
下面贴上关键代码。 接口IChatroom.java:
package mediator; public interface IChatroom { void forward(User from, User to, String message); } |
Chatroom.java:
package mediator; public class Chatroom implements IChatroom { @Override public void forward(User from, User to, String message) { // TODO Auto-generated method stub if (to!= null ) { to.receive(from, message); } } } |
抽象类User.java:
package mediator; public abstract class User { IChatroom room; public User(IChatroom room) { this .room = room; } public abstract void send(User to, String message); public abstract void receive(User from, String message); } |
MaleUser.java:
package mediator; public class MaleUser extends User { public MaleUser(IChatroom room) { super (room); // TODO Auto-generated constructor stub } @Override public void receive(User from, String message) { // TODO Auto-generated method stub System.out.println( "帅哥我收到了:" + message); } @Override public void send(User to, String message) { // TODO Auto-generated method stub room.forward( this , to, message); } } |
FemaleUser.java:
package mediator; public class FemaleUser extends User { public FemaleUser(IChatroom room) { super (room); // TODO Auto-generated constructor stub } @Override public void receive(User from, String message) { // TODO Auto-generated method stub System.out.println( "美女我收到了:" + message); } @Override public void send(User to, String message) { // TODO Auto-generated method stub room.forward( this , to, message); } } |
测试类TestClient.java:
package mediator; public class TestClient { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub IChatroom room = new Chatroom(); FemaleUser hcc = new FemaleUser(room); MaleUser fq = new MaleUser(room); MaleUser gq = new MaleUser(room); MaleUser lp = new MaleUser(room); //男给男发消息 gq.send(fq, "吃饭了没?" ); //男给女发消息 lp.send(hcc, "我也没吃饭" ); } } |
总结一下,Mediator改变了原来两个对象的耦合方式。
联系客服