Game Development Reference
In-Depth Information
public:
void AddObserver(Observer* observer);
void RemoveObserver(Observer* observer);
template <void (Observer::*Method)()>
void Notify();
};
The Notifier class defines a vector of pointers to Observer objects. There are complementary
methods to add and remove observers to the Notifier and finally a template method named Notify ,
which will be used to notify Observer objects of an event. Listing 23-7 shows the AddObserver and
RemoveObserver method definitions.
Listing 23-7. The AddObserver and RemoveObserver method definitions
template <typename Observer>
void Notifier<Observer>::AddObserver(Observer* observer)
{
assert(find(m_observers.begin(), m_observers.end(), observer) == m_observers.end());
m_observers.emplace_back(observer);
}
template <typename Observer>
void Notifier<Observer>::RemoveObserver(Observer* observer)
{
auto object = find(m_observers.begin(), m_observers.end(), observer);
if (object != m_observers.end())
{
m_observers.erase(object);
}
}
Adding an Observer is as simple as calling emplace_back on the m_observers vector . The assert is
used to inform us if we are adding more than one copy of each Observer to the vector. The remove
is achieved by using find to get an iterator to the object to be removed and calling erase if the
iterator is valid.
The Notify method uses a C++ feature that you have not seen so far, method pointers . A method
pointer allows us to pass the address of a method from a class definition that should be called on a
specific object. Listing 23-8 contains the code for the Notify method.
Listing 23-8. The Notifier<Observer>::Notify Method
template <typename Observer>
template <void(Observer::*Method)()>
void Notifier<Observer>::Notify()
{
for (auto& observer : m_observers)
{
(observer->*Method)();
}
}
 
Search WWH ::




Custom Search