标签:message single lin inter 模式 ica cat 问题: rgs
中介者模式(Mediator Pattern)
The Mediator pattern simplifies communication among objects in a system by introducing a single object that manages message distribution among other objects. The Mediator pattern promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
1、Mediator
-中介者定义一个接口用于与各同事对象通信。
2、ConcerteMediator
-具体中介者通过协调各同事对象实现写协作行为。
-了解并维护它的各个同事。
3、Colleague class
-每一个同事类都知道它的中介者对象。
-每一个同事对象在需与其他的同事通信的时候,与它的中介者通信。
abstract class Mediator { public abstract void register(Colleague colleague); public abstract void relay(Colleague cl); }
class ConcreteMediator extends Mediator { private List<Colleague> colleagues=new ArrayList<Colleague>(); public void register(Colleague colleague) { if(!colleagues.contains(colleague)) { colleagues.add(colleague); colleague.setMedium(this); } } public void relay(Colleague cl) { for(Colleague ob:colleagues) { if(!ob.equals(cl)) { ((Colleague)ob).receive(); } } } }
abstract class Colleague { protected Mediator mediator; public void setMedium(Mediator mediator) { this.mediator=mediator; } public abstract void receive(); public abstract void send(); }
class ConcreteColleague1 extends Colleague { public void receive() { System.out.println("Colleague1 receive。"); } public void send() { System.out.println("Colleague1 send。"); mediator.relay(this); } }
class ConcreteColleague2 extends Colleague { public void receive() { System.out.println("Colleague2 receive。"); } public void send() { System.out.println("Colleague2 send。"); mediator.relay(this); }
public class MediatorPattern { public static void main(String[] args) { Mediator md=new ConcreteMediator(); Colleague c1,c2; c1=new ConcreteColleague1(); c2=new ConcreteColleague2(); md.register(c1); md.register(c2); c1.send(); System.out.println("-------------"); c2.send(); } }
《设计模式:可复用面向对象软件的基础》
标签:message single lin inter 模式 ica cat 问题: rgs
原文地址:https://www.cnblogs.com/diameter/p/13215383.html