[C++]观察者模式

当对象间存在一对多关系时,则使用观察者模式(Observer Pattern)。比如,当一个对象被修改时,则会自动通知它的依赖对象。观察者模式属于行为型模式。

C++代码如下:

// 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

// 参考大话设计模式

#include 
#include  

using namespace std;

class Secretary;

class Observer {
public:
	//Observer() {}
	//Observer(string name, Secretary* secretary) {}
	virtual void Notify() {
	}

private:
	string _name;
	Secretary* _secretary;
};

class Secretary{
public:
	void addObserver(Observer* observer) {
		_observers.push_back(observer);
	}

	void removeObserver(Observer* observer) {
		vector::iterator p = _observers.begin();
		while (p != _observers.end())
		{
			if ((*p) == observer) {
				_observers.erase(p);
				break;
			}
			p++;
		}
	}

	void Notify() {
		vector::iterator p = _observers.begin();
		while (p != _observers.end())
		{
			(*p)->Notify();
			p++;
		}
	}

private:
	vector _observers;
};

class WorkerAObserver : public Observer {
public:
	WorkerAObserver(string name, Secretary* secretary) {
		_name = name;
		_secretary = secretary;
	}

	void Notify() {
		cout << "secretary notify:" << _name << " boss come" << endl;
	}

private:
	string _name;
	Secretary* _secretary;
};

class WorkerBObserver : public Observer {
public:
	WorkerBObserver(string name, Secretary* secretary) {
		_name = name;
		_secretary = secretary;
	}

	void Notify() {
		cout << "secretary notify:" << _name << " boss come" << endl;
	}

private:
	string _name;
	Secretary* _secretary;
};


int main()
{
	Secretary* secretary = new Secretary();

	WorkerAObserver* workerA = new WorkerAObserver("David", secretary);
	WorkerBObserver* workerB = new WorkerBObserver("Tom", secretary);
	secretary->addObserver(workerA);
	secretary->addObserver(workerB);

	secretary->Notify();

	cout << "remove workerA" << endl;

	secretary->removeObserver(workerA);
	secretary->Notify();

	return 0;
}


github源码路径:https://github.com/dangwei-90/Design-Mode

持续更新中

你可能感兴趣的:(C++)