观察者模式
通过本次实验掌握以下内容:
1、理解观察者模式的动机,掌握该模式的结构;
2、能够利用观察者模式解决实际问题。
实验任务:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
Client.java: 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(""); } } Holders.java: 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("股票比较稳定,还好还好"); } } } MyObserver.java: public interface MyObserver { void response(int rate); } MySubject.java: 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); } Stock.java: public class Stock extends MySubject { public void change(int rate) { for(Object obs : observers) { ((MyObserver)obs).response(rate); } } }
标签:总结,每日,11.27,System,rate,void,println,public,out From: https://www.cnblogs.com/-GYP/p/17860257.html