Lets learn "Observer Design Pattern"

 In this tutorial, we'll learn about the Observer design pattern as in what it is, in which scenario it is being used and how it works. If you've are not familiar with what are software design patterns and what are its different types check out this tutorial.

Introduction

An observer design pattern is a behavioral design pattern, As the name suggests, the Observer contains observe. So this design pattern is used when one or more entities observe the changes in an entity (or subject). 

Usecases

Let's learn this with an example, you must be familiar with subscriptions on youTube. When you subscribe to a channel you get notified if some new video is uploaded on that channel. Your subscribing means you are observing the channel for more content. Like you there can be many people who are subscribing to the same channel. So there are multiple observers which are observing a channel (or subject).
Basically, the observer pattern moves the pull model to push model which means instead of observers polling the subject for new data, the subject is responsible for pushing the new data. So all the subscriptions model like RSA feed, youTube subscriptions, etc. follow observer pattern.

Examples

#include<iostream>
#include<list>
#include<map>
using namespace std;

class Observer {
    int observerID;

    public:
    Observer(int id) {observerID = id;}

    int getID() {
        return observerID;
    }

    void update(int objID) {
        cout<<"Observer "<<observerID<<" received object with id: "<<objID<<endl;
    }
};

class Subject {
    private:
    map<int, Observer*> data;

    public:
    Subject() {}

    void registerObserver(Observer* obs) {
        data.insert(make_pair(obs->getID(), obs));
    }

    void unregisterObserver(int observerID) {
        if(data.find(observerID) != data.end()) {
            data.erase(observerID);
        }
    }

    void notify(int objID) {
        map<int, Observer*>::iterator itr = data.begin();
        while(itr != data.end()){
            itr->second->update(objID);
            itr++;
        }
    }
};

int main(){
    Observer *o1 = new Observer(1);
    Observer *o2 = new Observer(2);
    Observer *o3 = new Observer(3);

    Subject* s1 = new Subject();
    s1->registerObserver(o1);
    s1->registerObserver(o2);
    s1->registerObserver(o3);

    s1->notify(1234);
    return 0;

    // output
    // Observer 1 received object with id: 1234
    // Observer 2 received object with id: 1234
    // Observer 3 received object with id: 1234    
}

HOPE YOU LIKE THIS TUTORIAL. FEEL FREE TO COMMENT BELOW IF YOU HAVE ANY DOUBTS. AND STAY TUNED FOR MORE TUTORIALS :)
Happy Learning!

Comments

Popular posts from this blog

Lets learn "About kube proxy in iptables mode"

Lets learn "System design for paste bin (or any text sharing website)"

Lets learn "Factory design pattern"