Observer Pattern
//===================================================Observer.h============================================================//
template <class T>
class Observer
{
public:
/**
* Default constructor.
*/
Observer();
/**
* Destructor.
*/
virtual ~Observer();
/**
* Update.
* Observer updates the attributes of the subject.
* @param observee The constant reference subject.
*/
virtual void Update(T& observee, const float& timeDelta=0) = 0;
};
/**
* Observer subject
*/
template <class T>
class Subject
{
public:
/**
* Default constructor.
*/
Subject();
/**
* Destructor.
*/
virtual ~Subject();
/**
* Inserts an observer into the collection.
* @param observer The observer to insert.
*/
virtual void AddObserver(const Observer<T>& observer);
/**
* Removes all observer that compare equal to the one.
* @param observer The observer type to to delete.
*/
virtual void RemoveObserver(const Observer<T>* observer);
/**
* Walk through the observers and update each.
* @param observee The object to observe.
* @param timeDelta The time passed since the last call.
*/
virtual void NotifyAll(const T& observee, float timeDelta = 0);
private:
/// Observer collection/storage.
LinkedList<Observer<T>*> mObservers;
};
//===================================================Observer.cpp==========================================================//
#include "Observer.h"
template< class T >
Observer< T >::Observer()
{
}
template< class T >
Observer< T >::~Observer()
{
}
template< class T >
Subject< T >::Subject()
{
}
template< class T >
Subject< T >::~Subject()
{
mObservers.Clear();
}
template< class T >
void Subject< T >::AddObserver(const Observer< T >& observer)
{
mObservers.PushFront(observer);
}
template< class T >
void Subject< T >::RemoveObserver(const Observer< T >* observer)
{
mObservers.Remove(observer);
}
template< class T >
void Subject< T >::NotifyAll(const T& observee, float timeDelta)
{
for(LinkedList< Observer<T>* >::Iterator iterator = Begin(); iterator != End(); iterator++)
{
(*iterator).Update(observee, timeDelta);
}
}
'Programming Tip' 카테고리의 다른 글
[Digging] VS2005 원격디버깅 (0) | 2011.03.31 |
---|---|
[Digging] Memory Leak Detecting (0) | 2011.01.26 |