mardi 14 août 2018

Good way to create observer design pattern in C++

I am trying to implement observer design pattern in C++ as below

#include <iostream>
#include <vector>

using namespace std;

class observer
{
    public:
        observer() = default;
        ~observer() = default;

        virtual void notify() = 0;
};

class subject
{
    vector <observer *> vec;

    public:
        subject() = default;
        ~subject() = default;

        void _register(observer *obj)
        {
            vec.push_back(obj);
        }

        void unregister(observer *obj)
        {
            int i;
            for(i = 0; i < vec.size(); i++)
            {
                if(vec[i] == obj)
                {
                    cout << "found elem. unregistering" << endl;
                    vec.erase(vec.begin() + i);
                    break;
                }
            }

            if(i == vec.size())
            {
                cout << "elem not found to unregister" << endl;
            }
        }

        void notify()
        {
            vector <observer *>::iterator it = vec.begin();
            while(it != vec.end())
            {
                (*it)->notify();
                it ++;
            }
        }
};

class obsone : public observer
{
    void notify()
    {
        cout << "in obsone notify" << endl;
    }
};

class obstwo : public observer
{
    void notify()
    {
        cout << "in obstwo notify" << endl;
    }
};

int main()
{
    subject sub;

    obsone *one = new obsone();
    obstwo *two = new obstwo();

    sub._register(one);   
    sub._register(two);
    sub.notify();

    sub.unregister(one);
    sub.notify();

    //delete two;
    //sub.notify();

    return 0;
}

I am registering the objects with the subject explicitly. Is it the correct way of doing it or do I need to register through observer class only. Are there any problems with the above approach?

Aucun commentaire:

Enregistrer un commentaire