-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathsubject.h
102 lines (85 loc) · 2.77 KB
/
subject.h
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*
* Copyright (c) 2011, Intel Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _SUBJECT_H_
#define _SUBJECT_H_
#include <vector>
#include "observer.h"
/**
* This class implements the subject component of the subject/observer design
* pattern.
* @note This class does not throw exceptions.
*/
template <class TSubject, class TData>
class Subject
{
public:
Subject(TSubject *subject, TData initState = TData(), bool delta = false) :
mSubject(subject),
mCurState(initState),
mDeltaCheck(delta) { mFirstTime = true; }
virtual ~Subject() {}
void Attach(Observer<TSubject, TData> &observer)
{ mObservers.push_back(&observer); }
TData GetCurrentState() const { return mCurState; }
void Notify(const TData& newSt)
{
bool doUpdate = true;
if (mDeltaCheck) {
if ((mCurState == newSt) && (mFirstTime == false))
doUpdate = false;
}
mFirstTime = false;
if (doUpdate) {
mCurState = newSt;
LOG_DBG("Subject notifying observers of event");
for (size_t i = 0; i < mObservers.size(); i++)
(mObservers[i])->Update(static_cast<TSubject *>(this), newSt);
}
}
private:
TSubject *mSubject;
TData mCurState;
std::vector<Observer<TSubject, TData> *> mObservers;
/// Update() all observers on 1st Notify regardless of all other options
bool mFirstTime;
/// Update() all observers only when the state changes value
bool mDeltaCheck;
};
/**
* This class implements a state subject
* @note This class does not throw exceptions.
*/
template<class TSSData>
class StateSubject : public Subject<void, TSSData>
{
public:
StateSubject(TSSData initState = TSSData()) :
Subject<void, TSSData>(NULL, initState) {}
virtual ~StateSubject() {}
};
/**
* This class implements an object subject, i.e. a pure subject technique
* @note This class does not throw exceptions.
*/
template<class TOSSubject>
class PureSubject : public Subject<TOSSubject, bool>
{
public:
PureSubject(TOSSubject *subject) :
Subject<TOSSubject, bool>(subject, true) {}
virtual ~PureSubject() {}
};
#endif