设计模式-中介者模式(Mediator)
/**
*中介者模式在消息队列中的应用
*/
package test.mediator; public abstract class Message { private Messages messages; public void sendMessage(String messageFrom,String messageTo){ messages.send(messageFrom, messageTo); } public abstract void receiveMessage (Message messageFrom); public abstract String getName(); public Messages getMessages(){ return messages; } public void setMessages(Messages messages){ this.messages=messages; } }
package test.mediator; public class Message1 extends Message{ @Override public void receiveMessage(Message messageFrom) { System.out.println(messageFrom.getName()+"堵塞了"+getName()); } @Override public String getName() { return "消息队列1"; } }
package test.mediator; public class Message2 extends Message{ @Override public void receiveMessage(Message messageFrom) { System.out.println(messageFrom.getName()+"堵塞了"+getName()); } @Override public String getName() { return "消息队列2"; } }
package test.mediator; /** * 消息接口 * @author lenovo * */ public interface Messages { void send(String messageFrom,String messageTo); void add(Message message); }
package test.mediator; import java.util.HashMap; import java.util.Map; public class MessagesImpl implements Messages { @SuppressWarnings("rawtypes") private Map map=new HashMap(); @Override public void send(String messageFrom, String messageTo) { Message message1=(Message)map.get(messageFrom); Message message2=(Message)map.get(messageTo); message2.receiveMessage(message1); } @SuppressWarnings("unchecked") @Override public void add(Message message) { message.setMessages(this); map.put(message.getName(), message); } }
package test.mediator; public class Client { public static void main(String[] args) { Messages messages=new MessagesImpl(); Message a=new Message1(); Message b=new Message2(); messages.add(a); messages.add(b); a.sendMessage("消息队列1", "消息队列2"); } }