中介者模式,是把原来对象关系的操作放到一个中介类里面,然后重新封装。
public abstract class Colleage {
private int num ;
public int getNum() {
return num ;
}
public void setNum( int num) {
this .num = num;
}
public abstract void setEffect (Colleage c1,Colleage c2);
}
public class Colleage1 extends Colleage{
@Override
public void setEffect(Colleage c1, Colleage c2) {
c2.setNum(c1.getNum() * 2);
}
}
public class Colleage2 extends Colleage{
@Override
public void setEffect(Colleage c1, Colleage c2) {
c1.setNum(c2.getNum() * 2);
}
}
public abstract class AbstractMediator {
private Colleage c1;
private Colleage c2;
public AbstractMediator(Colleage c1, Colleage c2) {
this .c1 = c1;
this .c2 = c2;
}
public abstract void effect1 ();
public abstract void effect2();
}
public class Mediator extends AbstractMediator{
private Colleage c1 ;
private Colleage c2 ;
public Mediator(Colleage c1, Colleage c2) {
super (c1, c2);
this .c1 = c1;
this .c2 = c2;
}
public void effect1() {
c1 .setEffect(c1 , c2 );
System. out .println("c1:" + c1 .getNum());
System. out .println("c2:" + c2 .getNum());
}
public void effect2() {
c2 .setEffect( c1, c2);
System. out .println("c1:" + c1 .getNum());
System. out .println("c2:" + c2 .getNum());
}
}
public class MediatorClient {
public static void main(String[] args) {
Colleage c1 = new Colleage1();
c1.setNum(1);
Colleage c2 = new Colleage2();
c2.setNum(2);
AbstractMediator mediator = new Mediator(c1, c2);
mediator.effect1();
mediator.effect2();
}
}