行為型模式-中介者模式
阿新 • • 發佈:2018-12-21
行為型模式又可以分成以下四類:第一類:通過父類與子類的關係進行實現。第二類:兩個類之間。第三類:類的狀態。第四類:通過中間類
命令模式屬於第四類,通過中間類
我們來看一下兩個類之間是如何通過中間類來相互影響的
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 voidsetNumber(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()); } }
執行結果