当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
package 实验21观察者模式; import java.util.ArrayList; public class Fen{ private ArrayList<Guancha> oblist; public Fen(){ oblist=new ArrayList<>(); } public void add(Guancha a){ oblist.add(a); } public void remove(Guancha a){ oblist.remove(a); } public void sheng(double a){ if(a>0.05) for(Guancha guan:oblist){ guan.sheng(); } } public void jiang(double a){ if(a>0.05) for(Guancha guan:oblist){ guan.jiang(); } } }
package 实验21观察者模式; public interface Guancha { public void sheng(); public void jiang(); }
package 实验21观察者模式; public class Gumin implements Guancha{ private String name; public Gumin(String a){name=a;} public void sheng(){ System.out.println(name+"买了一些股票(股票升了)"); } public void jiang(){ System.out.println("股票降价了,哭了"); } }
package 实验21观察者模式; public class main { public static void main(String[] args) { Fen f=new Fen(); Gumin g1=new Gumin("第一个股民"); Gumin g2=new Gumin("第二个股民"); f.add(g1); f.add(g2); System.out.println("股票升了"); f.sheng(0.1); System.out.println("比率小于0.05"); System.out.println(); f.sheng(0.001); System.out.println("股票降了"); f.jiang(0.1); System.out.println("比率小于0.05"); System.out.println(); f.jiang(0.001); } }