设计模式-观察者模式
[实验任务]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
java代码
package experiment21; public interface AbstractObserver { void response(int n); } package experiment21; import java.util.ArrayList; public abstract class AbstractSubject { protected ArrayList observers = new ArrayList(); //注册方法 public void attach(AbstractObserver observer) { observers.add(observer); } //注销方法 public void detach(AbstractObserver observer) { observers.remove(observer); } public void up() {}; public void down() {}; } package experiment21; public class Client { public static void main(String []args) { AbstractSubject as=new ConcreteSubject(); AbstractObserver ao1=new ConcreteObserver("张三"); AbstractObserver ao2=new ConcreteObserver("李四"); AbstractObserver ao3=new ConcreteObserver("王五"); AbstractObserver ao4=new ConcreteObserver("赵六"); as.attach(ao1); as.attach(ao2); as.attach(ao3); as.attach(ao4); as.up(); System.out.println("****************"); as.down(); } } package experiment21; public class ConcreteObserver implements AbstractObserver{ private String name; public ConcreteObserver(String name) { this.name=name; } @Override public void response(int n) { // TODO Auto-generated method stub if(n==1) { System.out.println(name+" 买入!"); }else { System.out.println(name+" 大哭"); } } } package experiment21; import java.util.ArrayList; public class ConcreteSubject extends AbstractSubject{ @Override public void up() { // TODO Auto-generated method stub System.out.println("股票上涨"); for(Object obs:observers) { ((ConcreteObserver)obs).response(1); } } @Override public void down() { // TODO Auto-generated method stub System.out.println("股票下跌"); for(Object obs:observers) { ((ConcreteObserver)obs).response(0); } } }
c++代码
#include <string> #include <iostream> #include <vector> using namespace std; class guancha { virtual void sheng()=0; virtual void jiang()=0; }; class gumin { private: string name; public: gumin(string a) { name=a; } void sheng() { cout<<name<<"买了一些股票(股票升了)"<<endl; } void jiang() { cout<<name<<"买了一些股票(股票降了)"<<endl; } }; class fen { private: vector<gumin> obj; public: fen() {} void add(gumin g) { obj.push_back(g); } void remove() { obj.pop_back(); } }; int main() { gumin g1=gumin("第一个股民"); gumin g2=gumin("第二个股民"); fen f=fen(); f.add(g1); f.add(g2); cout<<"股票升了"<<endl; cout<<"张三买入"<<endl; cout<<"股票降了"<<endl; cout<<"张三大哭"<<endl; }