2010年6月27日 星期日

[IPhone] Observer with Game Development

Introduction
When I develop my game project. I use a global timer to update game scene, and game scene will update all game roles in game scene if need.
Background
After study observer, I think game scene is a observable and it can notify game role to update.
So I implement observer pattern in my game.

UML


Observer Code

class Observable;
class Observer : public NSObject
{
private:
// --- Add private member --- //
public:
// --- Add public member --- //
Observer();
virtual ~Observer();

virtual void Update() = 0;
};

typedef set<observer*> SET;

class Observable : public NSObject
{
private:
// --- Add private member --- //
SET m_observers;
public:
// --- Add public member --- //
Observable();
virtual~Observable();

void RegisterObserver(Observer *o);
void RemoveObserver(Observer *o);
void NotifyObservers();
};
void Observable::RegisterObserver(Observer *o)
{
m_observers.insert(o);
}
void Observable::RemoveObserver(Observer *o)
{
m_observers.erase(o);
}

void Observable::NotifyObservers()
{
SET::
reverse_iterator index;
SET::
reverse_iterator end = m_observers.rend();
for(index = m_observers.rbegin(); index != end; index++)
{
((Observer*)(*index))->Update();
}
}

沒有留言:

張貼留言

Hello