用一个中介者对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。
二、结构图
1) 抽象中介者:定义同事(Colleague)对象到中介者(Mediatior)对象的接口,通常是一个事件方法。
2) 具体中介者:具体中介者实现抽象中介者声明的方法。知晓所有的具体同事类,从具体同事接收消息向另外的具体同事类发送命令。
3) 抽象同事类:定义中介者到同事对象的接口,同事对象只知道中介者而不知道其他同事对象。
三、一个例子
import java.util.ArrayList;abstract class AbstractMediator{ public abstract void register(AbstractColleague ac); public abstract void ColleagueChanged(AbstractColleague ac); } abstract class AbstractColleague{ private AbstractMediator med; public AbstractColleague(AbstractMediator mediator){ this.med=mediator; } public abstract void action(); public void changed(){ med.ColleagueChanged(this); } } class ConcreteMediator extends AbstractMediator{ private ArrayList<AbstractColleague> colleagueList=new ArrayList<AbstractColleague>(); public void register(AbstractColleague ac) { colleagueList.add(ac); } public void ColleagueChanged(AbstractColleague ac) { for(int i=0;i<colleagueList.size();i++){ if(colleagueList.get(i)!=ac){ colleagueList.get(i).action(); } } } } class ConcreteColleagueA extends AbstractColleague{ public ConcreteColleagueA(AbstractMediator mediator){ super(mediator); mediator.register(this); } public void action() { System.out.println("AAAAAAAAAAAAAAA"); } } class ConcreteColleagueC extends AbstractColleague{ public ConcreteColleagueC(AbstractMediator mediator){ super(mediator); mediator.register(this); } public void action() { System.out.println("CCCCCCCCCCCCCCC"); } } class ConcreteColleagueB extends AbstractColleague{ public ConcreteColleagueB(AbstractMediator mediator){ super(mediator); mediator.register(this); } public void action() { System.out.println("BBBBBBBBBBBBBBB"); } } class test{ public static void main(String[] args){ AbstractMediator mediator=new ConcreteMediator(); AbstractColleague colleagueA=new ConcreteColleagueA(mediator); AbstractColleague colleagueB=new ConcreteColleagueB(mediator); AbstractColleague colleagueC=new ConcreteColleagueC(mediator); colleagueA.changed(); colleagueB.changed(); colleagueC.changed(); } }五、优缺点
原文:http://blog.csdn.net/lu930124/article/details/26957367