有时候,几个对象之间会相互影响,我们把这些会相互影响的对象叫做”同事“,如果我们显示地去执行他们之间的相互影响的话,代码会变得很臃肿并且难以维护。所以我们引入中介者来帮我们维护他们之间的相互关系,这样就减少了系统耦合。
比如,在一个能量守恒的系统里,两股能量是此消彼长,但总和不变。我们要用代码模拟并且每股能量都是单独的一个对象的话,这个关系我们便可以用中介者来维护。
package mediator; public abstract class AbstractEnergy { protected int energy; public AbstractEnergy(int energy) { this.energy=energy; } public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public abstract void changeEnergy(int changeValue, AbstractMediator mediator); } package mediator; public class Energy0 extends AbstractEnergy { public Energy0(int energy) { super(energy); // TODO Auto-generated constructor stub } @Override public void changeEnergy(int changeValue, AbstractMediator mediator) { // TODO Auto-generated method stub this.energy+=changeValue; mediator.aaffect1(this.energy); //影响能量1 } } package mediator; public class Energy1 extends AbstractEnergy { public Energy1(int energy) { super(energy); // TODO Auto-generated constructor stub } @Override public void changeEnergy(int changeValue, AbstractMediator mediator) { // TODO Auto-generated method stub this.energy+=changeValue; mediator.aaffect0(this.energy); //影响能量0 } } package mediator; public abstract class AbstractMediator { protected AbstractEnergy abstractEnergy0; protected AbstractEnergy abstractEnergy1; protected int sum; //系统总能量 public AbstractMediator(AbstractEnergy abstractEnergy0, AbstractEnergy abstractEnergy1) { super(); this.abstractEnergy0 = abstractEnergy0; this.abstractEnergy1 = abstractEnergy1; this.sum=abstractEnergy0.getEnergy()+abstractEnergy1.getEnergy(); } public abstract void aaffect0(int value1); public abstract void aaffect1(int value0); } package mediator; public class Mediator extends AbstractMediator { public Mediator(AbstractEnergy abstractEnergy0, AbstractEnergy abstractEnergy1) { super(abstractEnergy0, abstractEnergy1); // TODO Auto-generated constructor stub } @Override public void aaffect0(int value1) { // TODO Auto-generated method stub this.abstractEnergy0.setEnergy(this.sum-value1); } @Override public void aaffect1(int value0) { // TODO Auto-generated method stub this.abstractEnergy1.setEnergy(this.sum-value0); } } package mediator; public class Client { public static void main(String[] args) { // TODO Auto-generated method stub AbstractEnergy energy0=new Energy0(521); AbstractEnergy energy1=new Energy1(250); System.out.println("总能量为:" + (energy0.getEnergy()+energy1.getEnergy())); AbstractMediator mediator=new Mediator(energy0, energy1); energy0.changeEnergy(100, mediator); //第0股能量加100 System.out.println("第0股能量:"+energy0.getEnergy()); System.out.println("第1股能量:"+energy1.getEnergy()); energy1.changeEnergy(50, mediator); //第1股能量加50 System.out.println("第0股能量:"+energy0.getEnergy()); System.out.println("第1股能量:"+energy1.getEnergy()); System.out.println("总能量为:" + (energy0.getEnergy()+energy1.getEnergy())); } }
适用场景: