观察者模式
当对象间存在一对多关系时,则使用观察者模式(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