应用场景:
用中介者对象来封装一系列的对象交互,使得这些对象之间不需要显示的引用,从而使其耦合松散, 可
以独立的改变她们的交互.网状结构变成了星型结构了。
/**
* 抽象的同事类
* @author ZhangSheng
*
*/
public abstract class AbstractColleague {
public double number;
public abstract void affect(double number,AbstractMediator mediator);
}
------------------------------------------------------------------------------------------------------------
/**
* 同事A
* @author ZhangSheng
*
*/
public class Colleague_A extends AbstractColleague {
//若A想影响B,他不直接来作用,而是通过mediator来实现
@Override
public void affect(double number, AbstractMediator mediator) {
this.number = number;
mediator.a_affect_b();
}
}
--------------------------------------------------------------------------------------------------------
/**
* 同事B
* @author ZhangSheng
*
*/
public class Colleague_B extends AbstractColleague {
@Override
public void affect(double number, AbstractMediator mediator) {
this.number = number;
mediator.b_affect_a();
}
}
---------------------------------------------------------------------------------------------------------------
/**
* 抽象中介者,持有所有的同事类,维护同事类间的交互
* @author ZhangSheng
*
*/
public abstract class AbstractMediator {
public AbstractColleague colleague_A;
public AbstractColleague colleague_B;
public AbstractMediator(AbstractColleague colleague_A, AbstractColleague colleague_B) {
super();
this.colleague_A = colleague_A;
this.colleague_B = colleague_B;
}
public abstract void a_affect_b();
public abstract void b_affect_a();
}
---------------------------------------------------------------------------------------------------------------------------
/**
* 具体的交互
* @author ZhangSheng
*
*/
public class Mediator extends AbstractMediator {
public Mediator(AbstractColleague colleague_A, AbstractColleague colleague_B) {
super(colleague_A, colleague_B);
}
@Override
public void a_affect_b() {
colleague_B.number = colleague_A.number*20;
}
@Override
public void b_affect_a() {
colleague_A.number = colleague_B.number/20.0;
}
}
------------------------------------------------------------------------------------------------------------------------------
public class Test {
/**
* 测试类 用中介者对象来封装一系列的对象交互,使得这些对象之间不需要显示的引用,从而使其耦合松散, 可以独立的改变她们的交互
*/
public static void main(String[] args) {
AbstractColleague collA = new Colleague_A();
AbstractColleague collB = new Colleague_B();
AbstractMediator am = new Mediator(collA, collB);
System.out.println("==========通过设置A影响B==========");
collA.affect(10, am);
am.a_affect_b();
System.out.println("collA的number值为:" + collA.number);
System.out.println("collB的number值为A的20倍:" + collB.number);
System.out.println("==========通过设置B影响A==========");
collB.affect(100, am);
am.b_affect_a();
System.out.println("collB的number值为:" + collB.number);
System.out.println("collA的number值为B的0.05倍:" + collA.number);
}
}