The Subject and Observer

Let's look at a code example to understand this pattern better. There are a few different ways to implement this pattern, so we will discuss implementation strategies along the way:

class Observer 
{
public:
virtual ~Observer(void) {}
virtual void Update(float currentHealth, float maxHealth) = 0;
};

We start off with our Observer interface. As always, we make our destructor virtual. The only method we need is an Update method however, as always, the name isn't important. This is the method that the Subject will use to notify the Observers that something has changed. One thing you might notice is that the update is very specific. In this case, it has two floats as arguments. This is a dependency that might change and cause our code to break. We will address improvements a little later.

You might also notice that there is no member data. It could be possible to give the base class a pointer to the Subject, and have this class be responsible for registering and unregistering (subscribing and unsubscribing) with the Subject. We decided to move that behavior into the derived classes so we could keep the base class as simple as possible:

class Subject 
{
public:
virtual ~Subject(void) {}
virtual void RegisterObserver(Observer* pToAdd) = 0;
virtual void UnregisterObserver(Observer* pToRemove) = 0;
virtual void Notify(void) = 0;
};

Our Subject is almost as simple as the Observer. The key methods we need are ways for the Observers to subscribe and unsubscribe to the Subject. Here, we called those methods RegisterObserver and UnregisterObserver. We have also added a Notify method which will be used to call Update on all registered Observers. There is no reason that this method needs to be public or even exist at all. As long as the derived class calls Update on the registered Observers, we are using the pattern correctly.

Again, you will notice that there are no data members in this class. We could easily add a vector of Observer pointers here in the base class. In fact, we could easily implement these methods because they will almost always be the same. However, we have chosen to keep this class simple and let the derived classes choose how to implement these methods.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.119