Observer Design Pattern example in C++

//Observer Design pattern Best Example.
//Observer Design pattern is implemented using two classes.
//First is observable or subject class: in this class even occurs and to be notified to the registered observers.
//subject class contains attachObserver(), notifyObserver(),and other task.
//Second class is observer class: class which wants to be notified when some even occurs in observable or subject class.
//observer class contains a pure viryual function notify().
//Example:
//When any event like new blog/article is available in a website it should notify to all the registered users.
//So here Blog will derived from subject class and
//users want to get notified of new articles. So User will be derived from class observer
#include<iostream>
using namespace std;
#include <vector>
#include <typeinfo>
#include <string>

class Subject;//forward declaration

class Observer//class which are interested to get notified
{
public:
    virtual void notify(Subject* s) = 0;//pure virtual function
    virtual ~Observer() {};
};

class Subject//Class in which even take place
{
    vector<Observer *> observers;
protected:
    void notify_observers()
    {
        vector<Observer *>::iterator iter;
        for (iter = observers.begin(); iter != observers.end(); ++iter)
            (*iter)->notify(this);
    }

public:
    virtual ~Subject() {};
    void register_observer(Observer* o)//pusshing the attached observers in a vector
    {
        observers.push_back(o);
    }
};

class Blog : public Subject
{
public:
    Blog()
    {
        cout << "New Article Posted." << "\n";
    }

    void eventTriggerNewArticle()
    {
        cout << "The new article event is triggered." << "\n";
        notify_observers();
    }

int const get_Blog_id()
//int get_Blog_id()
{
return 21022015;
}
};

class User : public Observer
{
public:
    virtual void notify(Subject* s)
    {
        Blog *a;
        a = dynamic_cast<Blog*>(s);
       cout << a->get_Blog_id() << "\n";
    }
};

int main ()
{
    Blog newArticle = Blog();
    User u = User();
    newArticle.register_observer(&u);
    newArticle.eventTriggerNewArticle();
    return 0;
}
/*OUTPUT:
New Article Posted.
The new article event is triggered.
21022015
*/

No comments:

Post a Comment