一、用一箇中介者對象封裝一系列的對象交互java
二、爲何要使用中介者模式ide
abstract class AbstractColleague { protected int number; public int getNumber() { return number; } public void setNumber(int number){ this.number = number; } //注意這裏的參數再也不是同事類,而是一箇中介者 public abstract void setNumber(int number, AbstractMediator am); } class ColleagueA extends AbstractColleague{ public void setNumber(int number, AbstractMediator am) { this.number = number; am.AaffectB(); } } class ColleagueB extends AbstractColleague{ @Override public void setNumber(int number, AbstractMediator am) { this.number = number; am.BaffectA(); } } abstract class AbstractMediator { protected AbstractColleague A; protected AbstractColleague B; public AbstractMediator(AbstractColleague a, AbstractColleague b) { A = a; B = b; } public abstract void AaffectB(); public abstract void BaffectA(); } class Mediator extends AbstractMediator { public Mediator(AbstractColleague a, AbstractColleague b) { super(a, b); } //處理A對B的影響 public void AaffectB() { int number = A.getNumber(); B.setNumber(number*100); } //處理B對A的影響 public void BaffectA() { int number = B.getNumber(); A.setNumber(number/100); } } public class Client { public static void main(String[] args){ AbstractColleague collA = new ColleagueA(); AbstractColleague collB = new ColleagueB(); AbstractMediator am = new Mediator(collA, collB); System.out.println("==========經過設置A影響B=========="); collA.setNumber(1000, am); System.out.println("collA的number值爲:"+collA.getNumber()); System.out.println("collB的number值爲A的10倍:"+collB.getNumber()); System.out.println("==========經過設置B影響A=========="); collB.setNumber(1000, am); System.out.println("collB的number值爲:"+collB.getNumber()); System.out.println("collA的number值爲B的0.1倍:"+collA.getNumber()); } }
中介者模式的優勢this
適用場景code
中介者模式是一種比較經常使用的模式,也是一種比較容易被濫用的模式對象