观察者模式:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
java源代码:
(1)Client.java:
package shiyan21; public class Client { public static void main(String args[]) { MySubject subject = new Stock(); MyObserver obs1; obs1=new Holders(); subject.attach(obs1); System.out.println("****股票上涨****"); subject.change(5); System.out.println(""); System.out.println("****股票下跌****"); subject.change(-5); System.out.println(""); System.out.println("****股票稳定****"); subject.change(4); System.out.println(""); } }
(2)Holders.java:
package shiyan21; public class Holders implements MyObserver { public void response(int rate) { if(rate>=5) { System.out.println("股票上涨,买买买"); }else if(rate<=-5){ System.out.println("股票下跌,大哭一场"); }else { System.out.println("股票比较稳定,还好还好"); } } }
(3)MyObserver.java:
package shiyan21; public interface MyObserver { void response(int rate); }
(4)MySubject.java:
package shiyan21; import java.util.ArrayList; public abstract class MySubject { protected ArrayList<MyObserver> observers = new ArrayList<MyObserver>(); //注册方法 public void attach(MyObserver observer) { observers.add(observer); } //注销方法 public void detach(MyObserver observer) { observers.remove(observer); } //抽象通知方法 public abstract void change(int rate); }
(5)Stock.java:
package shiyan21; public class Stock extends MySubject { public void change(int rate) { for(Object obs : observers) { ((MyObserver)obs).response(rate); } } }
实现截图: