观察者模式

观察者模式其实最好的名称应该是“发布订阅”模式
在目标subject状态改变的时候被动的唤醒观察者进行相应的处理

#include
using namespace std;

#include
/*观察者模式
* 目标subject被修改时,所有订阅该目标的观察者observer都会得到通知
*/

class Subject;
class Observer;
class Observer
{
public:
	virtual ~Observer() {}
	virtual void update(Subject* obj) = 0;
	Observer() {}
};

class Subject
{
public:
	virtual void add(Observer* obs)
	{
		observers.push_back(obs);
	}
	virtual void remove()
	{
		observers.pop_back();
	}
	virtual void notifyObservers()
	{
		for (auto x : observers)
			x->update(this);
	}
	virtual int getNum() { return 0; };
	virtual void execute() {};
	virtual ~Subject() {};

private:
	list<Observer*> observers;
};


class ConcreteSubject:public Subject
{
public:
	int getNum() { return num; }
	void execute()
	{
		for (int i = 0; i < 10; i++)
		{
			num += i;
			notifyObservers();
		}
	}
private:
	int num=10;
};


class GraphObserver :public Observer
{
public:
	void update(Subject* obj)
	{
		cout << "Graph Observer:";
		for (int i = 0; i < obj->getNum(); i++)
			cout << '*';
		cout << '\n';
	}
};

class DigitalObserver :public Observer
{
public:
	void update(Subject* obj)
	{
		cout << "Digital Observer:" << obj->getNum() << endl;
	}
};

int main()
{
	Subject* obj=new ConcreteSubject;
	obj->add(new DigitalObserver());
	obj->add(new GraphObserver());
	obj->execute();
	return 0;
}

你可能感兴趣的:(设计模式,观察者模式)