中介者模式
一、问题
用一个中介对象来封装一系列对象的交互,好多对象之间交互,会形成错综复杂的网络,类和类之间相互引用,表现形式是多对多,为了改变这种紧耦合的情况,引入中介者,用中介者与各个类进行交互,形成一个星形的网络,中介者在星形网络的中间,其余的对象组成网络的每一个边
二、类图和实例
(1)未使用中介者(联合国)之前的国与国家之间的联系
(2)使用了中介者之后,国与国之间联系通过联合国进行联系
(3)类图设计
三、实现
(1)抽象中介者用于定义格式 具体中介者用于定义那几个类之间有关系,他们彼此之间是怎么联系的
public abstract class Mediator { public abstract void send(String message, Colleague colleague); } public class ConcreteMediator extends Mediator { private ColleagueOne one; private ColleagueTwo two; public void setColleagueOne(ColleagueOne one) { this.one = one; } public void setColleagueTwo(ColleagueTwo two) { this.two = two; } @Override public void send(String message, Colleague colleague) { if(colleague == one) { two.notify(message); } else { one.notify(message); } } }
(2)同事类 用于定义错综复杂的各种类 以及他们用哪一个中介者
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } public abstract void send(String message); } public class ColleagueOne extends Colleague { public ColleagueOne(Mediator mediator) { super(mediator); } @Override public void send(String message) { this.mediator.send(message, this); } public void notify(String message) { System.out.println("同事一得到消息"+message); } } public class ColleagueTwo extends Colleague { public ColleagueTwo(Mediator mediator) { super(mediator); } @Override public void send(String message) { this.mediator.send(message, this); } public void notify(String message) { System.out.println("同事二得到消息"+message); } }
(3)客户测试类 client
public class Client { public static void main(String[] args) { ConcreteMediator mediator = new ConcreteMediator(); ColleagueOne one = new ColleagueOne(mediator); ColleagueTwo two = new ColleagueTwo(mediator); mediator.setColleagueOne(one); mediator.setColleagueTwo(two); one.send("hello I'm sunshisong"); two.send("hello, I'm yangpiao"); } }