pad.mattdiesel.co.uk

Snippet - Observer pattern c++ implementation

Observer pattern c++ implementation (C++)


Created 2016-03-24 14:05:19.103040 by Matt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <forward_list>


class observer
{
public:
    virtual void EventHandler() = 0;
};


class subject
{
private:
    std::forward_list<observer*> _observers;

protected:
    bool notifyObservers() {
        for (auto obs : _observers) {
            obs->EventHandler();
        }
    }

public:
    bool registerObserver(observer* obs) {
        _observers.push_front(obs);
    }

    bool unregisterObserver(observer* obs) {
        _observers.remove(obs);
    }

    subject()
        : _observers() {
    }
};




class MySubject : public subject {
private:
    int _state;
public:
    MySubject() : _state(0) {}

    void setState(int value) {
        if (value != _state) {
            _state = value;
            notifyObservers();
        }
    }

    void Step() {
        setState(_state + 1);
    }
};


class MyObserver : public observer
{
public:
    void EventHandler() {
        std::cout << "Event!" << std::endl;
    }
};



int main(int argc, char const *argv[])
{
    MyObserver obs;

    MySubject subj;
    subj.registerObserver(&obs);

    subj.Step();
    subj.Step();
    subj.Step();
    subj.Step();

    subj.unregisterObserver(&obs);

    return 0;
}