分类:
2008-09-11 14:33:03
源自:
Mediator中介者模式:
用一个中介者对象来封装一系列的对象交互。中介者使各对象不需要显式的相互引用,从而使其耦合松散,而且可以独立的改变他们之间的交互。
例子:
view plaincopy to clipboardprint?
public abstract class AbstractMediator {
public abstract void register(AbstractColleague ac);
public abstract void ColleagueChanged(AbstractColleague ac);
}
public class ConcreteMediator extends AbstractMediator {
private ArrayList
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();
}
}
}
}
public abstract class AbstractColleague {
private AbstractMediator med;
public AbstractColleague(AbstractMediator mediator) {
this.med = mediator;
}
public abstract void action();
public void changed() {
med.ColleagueChanged(this);
}
}
public class ConcreteColleagueA extends AbstractColleague {
public ConcreteColleagueA(AbstractMediator mediator) {
super(mediator);
mediator.register(this);
}
public void action() {
System.out.println("AAAAAAAAAAAAAAA");
}
}
public class ConcreteColleagueB extends AbstractColleague {
public ConcreteColleagueB(AbstractMediator mediator) {
super(mediator);
mediator.register(this);
}
public void action() {
System.out.println("BBBBBBBBBBBBBBB");
}
}
public class ConcreteColleagueC extends AbstractColleague {
public ConcreteColleagueC(AbstractMediator mediator) {
super(mediator);
mediator.register(this);
}
public void action() {
System.out.println("CCCCCCCCCCCCCCC");
}
}
public class Client {
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();
}
}