What is Observer Pattern?
* This is a behavioral design pattern.
* Observer pattern is used to solve the problem of notifying multiple objects of a change to keep them in sync like the Model-View-Controller concept.
* Useful for event management kind of scenarios.
* Two classes are involved.
* The Observable class is where the actual data change is occuring. It has information about all the interested objects that need to be notified.
* The Observer is typically an abstract class providing the interface to which concrete classes interested in the events need to be compliant to.
EXAMPLE: Demonstrate the implementation of observer design pattern
#include
#include
using namespace std;
// ---------------- Observer interface -----------------
class MyObserver {
public:
virtual void Notify() = 0;
};
// ---------------- Observable object -------------------
class MyObservable {
static MyObservable* instance;
set observers;
MyObservable() { };
public:
static MyObservable* GetInstance();
void AddObserver(MyObserver& o);
void RemoveObserver(MyObserver& o);
void NotifyObservers();
void Trigger();
};
MyObservable* MyObservable::instance = NULL;
MyObservable* MyObservable::GetInstance()
{
if ( instance == NULL ) {
instance = new MyObservable();
}
return instance;
}
void MyObservable::AddObserver(MyObserver& o)
{
observers.insert(&o);
}
void MyObservable::RemoveObserver(MyObserver& o)
{
observers.erase(&o);
}
void MyObservable::NotifyObservers()
{
set::iterator itr;
for ( itr = observers.begin();
itr != observers.end(); itr++ )
(*itr)->Notify();
}
// TEST METHOD TO TRIGGER
// IN THE REAL SCENARIO THIS IS NOT REQUIRED
void MyObservable::Trigger()
{
NotifyObservers();
}
// ------ Concrete class interested in notifications ---
class MyClass : public MyObserver {
MyObservable* observable;
public:
MyClass() {
observable = MyObservable::GetInstance();
observable->AddObserver(*this);
}
~MyClass() {
observable->RemoveObserver(*this);
}
void Notify() {
cout << "Received a change event" << endl;
}
};
void main()
{
MyObservable* observable = MyObservable::GetInstance();
MyClass* obj = new MyClass();
observable->Trigger();
}
OUTPUT:
Received a change event
What is Observer Pattern?
最新推荐文章于 2021-02-20 21:34:55 发布
