标签:
用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
package com.roc.mediator; /** * 抽象中介者类 * @author liaowp * */ public abstract class Mediator { public abstract void send(String message,Colleague colleague); }
package com.roc.mediator; public class ConcreteMediator extends Mediator{ private Colleague1 colleague1; private Colleague2 colleague2; public void setColleague1(Colleague1 colleague1) { this.colleague1 = colleague1; } public void setColleague2(Colleague2 colleague2) { this.colleague2 = colleague2; } public void send(String message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); }else{ colleague1.Notify(message); } } }
package com.roc.mediator; /** * 抽象同事类 * @author liaowp * */ public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator){ this.mediator=mediator; } }
package com.roc.mediator; public class Colleague1 extends Colleague{ public Colleague1(Mediator mediator) { super(mediator); } public void send(String message){ mediator.send(message, this); } public void Notify(String message){ System.out.println("同事1得到消息:"+message); } }
package com.roc.mediator; public class Colleague2 extends Colleague{ public Colleague2(Mediator mediator) { super(mediator); } public void send(String message){ mediator.send(message, this); } public void Notify(String message){ System.out.println("同事2得到消息:"+message); } }
package com.roc.mediator; /** * 中介者模式 * @author liaowp * */ public class Client { public static void main(String[] args) { ConcreteMediator mediator=new ConcreteMediator(); Colleague1 colleague1=new Colleague1(mediator); Colleague2 colleague2=new Colleague2(mediator); mediator.setColleague1(colleague1); mediator.setColleague2(colleague2); colleague1.send("最近还好吗?"); colleague2.send("还不错"); } }
标签:
原文地址:http://www.cnblogs.com/liaoweipeng/p/5791068.html