packagecn.imcompany.observer.stock;/**
* Created by tomyli on 2018/6/23.
* Github: https://github.com/peng051410
*/publicinterfaceBuyer{voidsetName(Stringname);StringgetName();voidhappy();voidsad();}
packagecn.imcompany.observer.stock;/**
* Created by tomyli on 2018/6/23.
* Github: https://github.com/peng051410
*/publicclassConcrectBuyerimplementsBuyer{privateStringname;@OverridepublicvoidsetName(Stringname){this.name=name;}@OverridepublicStringgetName(){returnname;}@Overridepublicvoidhappy(){System.out.println(this.getName()+":happy");}@Overridepublicvoidsad(){System.out.println(this.getName()+":sad");}}
具体的股民实现了喜与悲的方法,这样观察者已经准备就绪。下面来定义股票软件:
1
2
3
4
5
6
7
8
9
10
11
12
packagecn.imcompany.observer.stock;/**
* Created by tomyli on 2018/6/23.
* Github: https://github.com/peng051410
*/publicinterfaceStockSoft{voidgoUp();voidgoDown();}
packagecn.imcompany.observer.stock;importjava.util.ArrayList;importjava.util.List;/**
* Created by tomyli on 2018/6/23.
* Github: https://github.com/peng051410
*/publicclassConcreteStockSoftimplementsStockSoft{privateList<Buyer>buyerList;publicConcreteStockSoft(){this.buyerList=newArrayList<>();}publicvoidjoin(Buyerbuyer){buyerList.add(buyer);}publicvoidquit(Buyerbuyer){buyerList.remove(buyer);}@OverridepublicvoidgoUp(){buyerList.forEach(Buyer::happy);}@OverridepublicvoidgoDown(){buyerList.forEach(Buyer::sad);}}
packagecn.imcompany.observer.stock;/**
* Created by tomyli on 2018/6/23.
* Github: https://github.com/peng051410
*/publicclassStockTest{publicstaticvoidmain(String[]args){ConcreteStockSoftniuStock=newConcreteStockSoft();ConcrectBuyerbuyer1,buyer2,buyer3;buyer1=newConcrectBuyer();buyer1.setName("buyer1");buyer2=newConcrectBuyer();buyer2.setName("buyer2");buyer3=newConcrectBuyer();buyer3.setName("buyer3");niuStock.join(buyer1);niuStock.join(buyer2);niuStock.join(buyer3);niuStock.goUp();niuStock.quit(buyer1);niuStock.goDown();}}