21.观察者模式
[实验任务一]:股票提醒
当股票的价格上涨或下降5%时,会通知持有该股票的股民,当股民听到价格上涨的消息时会买股票,当价格下降时会大哭一场。
类图
代码
Java
Client.java
package test21;
public class Client {
public static void main(String[] args) {
Observer observer = new PersonObserver();
ConcreteSubject subject = new ConcreteSubject();
subject.attach(observer);
subject.setState("上涨");
subject.notifyy();
subject.setState("下跌");
subject.notifyy();
}
}
ConcreteSubject.java
package test21;
public class ConcreteSubject extends Subject{
private String state;
public void setState(String state) {
this.state = state;
}
@Override
public void notifyy() {
if(state.equals("上涨")) {
for (Object observer : observers) {
((Observer) observer).up_update();
}
}else if (state.equals("下跌")){
for (Object observer : observers) {
((Observer) observer).down_update();
}
}
}
}
Observer.java
package test21;
public interface Observer {
public void up_update();
public void down_update();
}
PersonObserver.java
package test21;
public class PersonObserver implements Observer{
@Override
public void up_update() {
System.out.println("买股票");
}
@Override
public void down_update() {
System.out.println("大哭一场");
}
}
Subject.java
package test21;
import java.util.ArrayList;
public abstract class Subject {
protected ArrayList observers = new ArrayList();
public void attach(Observer observer){
observers.add(observer);
}
public void detach(Observer observer){
observers.remove(observer);
}
public abstract void notifyy();
}
C++代码
#include <iostream>
#include <vector>
using namespace std;
//抽象观察者类
class Observer{
public:
virtual void up_update(){}
virtual void down_update(){}
};
//抽象物体类
class Subject{
protected:
vector<Observer*> ob;
public:
void attach(Observer *observer){
ob.push_back(observer);
}
void detach(){
ob.pop_back();
}
virtual void notify(){}
};
//具体观察者类
class PersonObserver: public Observer{
public:
void up_update(){
cout<<"股票上涨,开始买股票"<<endl;
}
void down_update(){
cout<<"股票下跌,股民大哭"<<endl;
}
};
//具体物体来
class ConcreteSubject: public Subject{
private:
string state;
public:
void setState(string state){
this->state = state;
}
void notify(){
for (int i=0; i<ob.size() ; i++) {
if(state=="上涨")
ob[i]->up_update();
else
ob[i]->down_update();
}
}
};
int main(){
ConcreteSubject *subject = new ConcreteSubject();
PersonObserver *observer = new PersonObserver();
subject->attach(observer);
subject->setState("上涨");
subject->notify();
subject->setState("下跌");
subject->notify();
}