行为型模式-中介者模式
Posted liunianfeiyu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了行为型模式-中介者模式相关的知识,希望对你有一定的参考价值。
行为型模式又可以分成以下四类:第一类:通过父类与子类的关系进行实现。第二类:两个类之间。第三类:类的状态。第四类:通过中间类
命令模式属于第四类,通过中间类
我们来看一下两个类之间是如何通过中间类来相互影响的
package behavior.pattern.intermediator.mediator; public abstract class AbstractColleague { protected float number; public float getNumber() { return number; } public void setNumber(float number){ this.number = number; } //注意这里的参数不再是同事类,而是一个中介者 public abstract void setNumber(float number, AbstractMediator am); }
package behavior.pattern.intermediator.mediator; public class ColleagueA extends AbstractColleague { public void setNumber(float number, AbstractMediator am) { this.number = number; am.AaffectB(); } }
package behavior.pattern.intermediator.mediator; public class ColleagueB extends AbstractColleague { @Override public void setNumber(float number, AbstractMediator am) { this.number = number; am.BaffectA(); } }
package behavior.pattern.intermediator.mediator; public 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(); }
package behavior.pattern.intermediator.mediator; import org.apache.commons.math3.util.Precision; public class Mediator extends AbstractMediator { public Mediator(AbstractColleague a, AbstractColleague b) { super(a, b); } //处理A对B的影响 public void AaffectB() { float number = A.getNumber(); B.setNumber(number*10); } //处理B对A的影响 public void BaffectA() { float number = B.getNumber(); A.setNumber(Precision.round(number/10, getDecimalDigit(number) + 1)); } private int getDecimalDigit(float number) { int digit = 0; String numberString = String.valueOf(number); if(numberString.indexOf(".") != -1) { digit = numberString.substring(numberString.indexOf(".") + 1).length(); } else { digit = 0; } return digit; } }
测试代码
package behavior.pattern.intermediator.mediator; 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(1001, am); System.out.println("collA的number值为:"+collA.getNumber()); System.out.println("collB的number值为A的10倍:"+collB.getNumber()); System.out.println("==========通过设置B影响A=========="); collB.setNumber(10.02F, am); System.out.println("collB的number值为:"+collB.getNumber()); System.out.println("collA的number值为B的0.1倍:"+collA.getNumber()); } }
运行结果
以上是关于行为型模式-中介者模式的主要内容,如果未能解决你的问题,请参考以下文章
设计模式(30)-----行为型模式-----中介者设计模式