观察者模式
[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
java实现
package observer; import java.util.ArrayList; public abstract class Subject { protected ArrayList<MyObserver> observers = new ArrayList<>(); //注册 public void attach(MyObserver obs){ observers.add(obs); } //注销 public void detach(MyObserver obs){ observers.remove(obs); } //抽象改变 public abstract void up(double a); public abstract void down(double a); }
package observer; public interface MyObserver { void responseUp(); void responseDown(); }
package observer; //股票,具体目标类 public class Stock extends Subject{ @Override public void up(double a) { System.out.println("股票上涨"+(a*100)+"%"); if(a>0.05){ for (MyObserver observer : observers) { observer.responseUp(); } } } @Override public void down(double a) { System.out.println("股票下跌"+(a*100)+"%"); if(a>0){ for (MyObserver observer : observers) { observer.responseDown(); } } } }
package observer; public class StockHolder implements MyObserver{ @Override public void responseUp() { System.out.println("股票上涨,买了一些股票"); } @Override public void responseDown() { System.out.println("股票下跌,哭了"); } }
package observer; public class Client { public static void main(String[] args) { Subject s = new Stock(); StockHolder h1 = new StockHolder(); s.attach(h1); s.up(0.06); System.out.println("-------------------"); s.down(0.06); } }
c++实现
// Created by 贾梓钊 #include<iostream> #include<list> using namespace std; class MyObserver { ;; public: virtual void responseUp(){} virtual void responseDown(){} }; class MySubject{ protected: list<MyObserver*> obs; public: void attach(MyObserver *ob){ obs.push_back(ob); } void detach(MyObserver *ob){ obs.remove(ob); } virtual void up(double a)=0; virtual void down(double a)=0; }; class StockHolder:public MyObserver{ public: void responseUp(){ cout<<"股票上涨,购买一些股票"<<endl; } void responseDown(){ cout<<"股票下跌,大哭一场"<<endl; } }; class Stock:public MySubject{ public: void up(double a){ cout<<"股票上涨"<<(a*100)<<"%"<<endl; list<MyObserver*>::iterator iter=obs.begin(); if(a>0.05){ for(;iter!=obs.end();iter++){ (*iter)->responseUp(); } } } void down(double a){ cout<<"股票下跌"<<(a*100)<<"%"<<endl; list<MyObserver*>::iterator iter=obs.begin(); if(a>0.05){ for(;iter!=obs.end();iter++){ (*iter)->responseDown(); } } } }; int main(){ MySubject *subject = new Stock(); MyObserver *mo=new StockHolder(); subject->attach(mo); subject->up(0.06); cout<<"----------------------"<<endl; subject->down(0.07); return 0; }