Broker Mode: to reduce the direct contact of individual objects, a mediation object is introduced to handle complex operations between objects.
Just like the seller's intermediary. Help to maintain communication between tenants and landlords.
Example Description: House buying and selling intermediary. Sellers and buyers know intermediaries, but buyers and sellers don't know each other.
Define an intermediary (Singleton implementation)
PackageCom.zpj.designMode.MediatorPattern;Importjava.util.ArrayList;Importjava.util.List; Public classMediator {List<Operator> opers =NewArraylist<operator>(); Public voidaddoperators (Operator oper) {opers.add (oper); } Private StaticMediator Mediator =NewMediator (); PrivateMediator () {} Public StaticMediator getinstance () {returnMediator; } Public voidSell (Operator Oper,intPrice ) {System.out.println ("---------For Sale:" + price + "$"); for(inti = 0; I < opers.size (); i++) {Operator op=Opers.get (i); if(Oper! =op) { if(Op.topprice >Price ) {op.buy (); } } } }}
Define an Operator abstract class
PackageCom.zpj.designMode.MediatorPattern; Public Abstract classOperator {protectedMediator Mediator =mediator.getinstance (); protected intTopprice = 0; PublicOperator (intTopprice) { Super(); This. Topprice =Topprice; } Public Abstract voidSellintPrice ); Public Abstract voidbuy ();}
Add two examples of house-speculators:
PackageCom.zpj.designMode.MediatorPattern; Public classOperator01extendsOperator { PublicOperator01 (intBaseprice) { Super(Baseprice); } @Override Public voidSellintPrice ) {Mediator.sell ( This, Price); } @Override Public voidBuy () {System.out.println ("Operator01-----------I buy!" "); }} PackageCom.zpj.designMode.MediatorPattern; Public classOperator02extendsOperator { PublicOperator02 (intBaseprice) { Super(Baseprice); } @Override Public voidSellintPrice ) {Mediator.sell ( This, Price); } @Override Public voidBuy () {System.out.println ("Operator02-----------I buy!" "); }}
Examples of Use:
PackageCom.zpj.designMode.MediatorPattern;Importorg.junit.Test; Public classTestunit {@Test Public voidtest01 () {Mediator Mediator=mediator.getinstance (); Operator OP01=NewOperator01 (12); Operator OP02=NewOperator02 (20); Mediator.addoperators (OP01); Mediator.addoperators (OP02); //02 SellersOp02.sell (1); }}
It is important to note that operator can not know each other, but mediator and each operator are aware of each other.
----------------------
Design mode-Mediator mode