C++ 设计模式:观察者模式

观察者模式

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

主要解决:一个对象状态改变给其他对象通知的问题,而且要考虑到易用和低耦合,保证高度的协作。

 示例代码:

subject.h

#pragma once
#include <list>
using namespace std;
class Observer;
class Subject
{
public:
	int getState();
	void setState(int state);
	void attach(Observer* pObserver);
	void notifyAllObservers();
private:
	list<Observer*> observers;
	int state;
};

subject.cpp

#include "Subject.h"
#include "Observer.h"
int Subject::getState()
{
	return state;
}

void Subject::setState(int state)
{
	this->state = state;
	notifyAllObservers();
}

void Subject::attach(Observer* pObserver)
{
	observers.push_back(pObserver);
}

void Subject::notifyAllObservers()
{
	for (auto it : observers)
	{
		it->update();
	}
}

observer.h

#pragma once
class Subject;
class Observer
{
public:
	Subject* subject;
	virtual void update() = 0;
};

class Observer1 :public Observer
{
public:
	Observer1(Subject* subject);
	virtual void update();
};

class Observer2 :public Observer
{
public:
	Observer2(Subject* subject);
	virtual void update();
};

class Observer3 :public Observer
{
public:
	Observer3(Subject* subject);
	virtual void update();
};

 

observer.cpp

#include "Observer.h"
#include "Subject.h"
#include <iostream>
using namespace std;
Observer1::Observer1(Subject* subject)
{
	this->subject = subject;
	this->subject->attach(this);
}

void Observer1::update()
{
	cout << "Observer1::update:" << subject->getState() << endl;
}

Observer2::Observer2(Subject* subject)
{
	this->subject = subject;
	this->subject->attach(this);
}

void Observer2::update()
{
	cout << "Observer2::update:" << subject->getState() << endl;
}

Observer3::Observer3(Subject* subject)
{
	this->subject = subject;
	this->subject->attach(this);
}

void Observer3::update()
{
	cout << "Observer3::update:" << subject->getState() << endl;
}

main.cpp

#include "Observer.h"
#include "Subject.h"
#include <iostream>
using namespace std;
void main()
{
	Subject *pSubject = new Subject();
	Observer* p1 = new Observer1(pSubject);
	Observer* p2 = new Observer2(pSubject);
	Observer* p3 = new Observer3(pSubject);
	pSubject->setState(0);
	pSubject->setState(1);
	pSubject->setState(2);
	int d;
	cin >> d;
}

运行结果:

Observer1::update:0
Observer2::update:0
Observer3::update:0
Observer1::update:1
Observer2::update:1
Observer3::update:1
Observer1::update:2
Observer2::update:2
Observer3::update:2

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值