Observer Pattern

What is the observer pattern used for, and why do we need it? If you’ve heard of the Model-View-Controller architectural pattern, let me tell you that underlying that is the Observer pattern. Observer is so widely used that java put it in its core library (java.util.Observer) and C# baked it right into the language (the event keyword).

In game development we have so many classes that do very different things. It’s good to keep them as decoupled as possible, but sometimes that is very hard. The observer pattern is a great tool to keep your code decoupled very easily.

Achievement System

Let’s say that we want to implement an achievement system. We can have so many different achievements like “Make 20 consecutive headshots”, “Beat the game under 3 hours”, “Fall from high height without dying”. Unlocking these achievements means that we have to make calls to some methods in many different places in our code. Let’s take for example the “Fall from high height without dying”. As you can guess this achievement is somehow tied to the Physics Engine, but do we really want to see a call to AchievementsManager.Unclock(Achievement.FallFromHighHeightWithoutDying) right in the middle of our collision detection or something? How do we avoid that?

That’s what the observer pattern is for. It lets one piece of code announce that something interesting happened without actually caring who receives the notification.

Imagine that our game world consists of entities. The interface for our entities is something like this:

public interface IEntity
{
    void PhysicsUpdate();

    // Other methods
}

The Physics Engine is responsible to update the physics of all entities in the game world. Our character is also an entity, and his PhysicsUpdate() method may look something like this:

public class Character : IEntity
{
    public virtual void PhysicsUpdate()
    {
        // Apply gravity and stuff...

        if (this.FellFromHighHeightWithoutDying())
        {
            AchievementsManager.Unlock(Achievement.FallFromHighHeightWithoutDying);
        }
    }

    // Other code...
}

We want to get rid of the call that unlocks the achievement through our AchievementsManager, because this way we couple the achievements system with our character. We are going to replace it with a call to another method:

NotifyObservers(this, Event.FallFromHighHeightWithoutDying);

This single line of code just says: “Look, I don’t know if anybody cares, but this entity just fell from high height without dying”. If someone cares however, he knows what to do. That someone is actually the observer. There can also be more than one observer, but let’s not get ahead of ourselves. Now we are decoupled from the AchievementsManager, but where did we actually get the NotifyObservers method from? All I can say is that it’s part of the big picture. Now lets draw that picture.

The Observer

Let’s start with the observer class. All observers observe for something interesting to happen. The interface for all observers is as follows.

public interface IObserver
{
    void OnNotify(IEntity entity, Event ev);
}

In our case the observer is the AchievementsManager.

public class AchievementsManager : IObserver
{
    public void OnNotify(IEntity entity, Event ev)
    {
        switch (ev)
        {
            case Event.FallFromHighHeightWithoutDying:
                bool isEntityCharacter = (entity as Character) != null;
                if (isEntityCharacter)
                {
                    this.UnlockAchievement(Achievement.FallFromHighHeightWithoutDying);
                }

                break;

            // Other cases...
        }
    }

    private void UnlockAchievement(Achievement achievement)
    {
        // Unlock if not already unlocked...
    }
}

The Observable Objects

The observable objects are the objects that are being observed by observers. These objects must also notify the observers if anything interesting happened. Let’s implement the interface for all observable objects. We need to be able to add, remove and notify any observers.

public interface IObservable
{
    void AddObserver(IObserver observer);

    void RemoveObserver(IObserver observer);

    void NotifyObservers(IEntity entity, Event ev);
}

In our case the observable object is our Character.

public class Character : IEntity, IObservable
{
    private List<IObserver> observers;

    // IEntity interface implementation
    public virtual void PhysicsUpdate()
    {
        // Apply gravity and stuff...

        if (this.FellFromHighHeightWithoutDying())
        {
            this.NotifyObservers(this, Event.FallFromHighHeightWithoutDying);
        }
    }
    // END IEntity interface implementation

    // IObservable interface implementation
    public virtual void AddObserver(IObserver observer)
    {
        this.observers.Add(observer);
    }

    public virtual void RemoveObserver(IObserver observer)
    {
        this.observers.Remove(observer);
    }

    public virtual void NotifyObservers(IEntity entity, Event ev)
    {
        foreach (var observer in this.observers)
        {
            observer.OnNotify(entity, ev);
        }
    }
    // END IObservable interface implementation
}

Now you see how it works. Our character is being observed by the achievement system. However, he actually doesn’t know that. He only knows that maybe he is being or is not being observed (sounds spooky :D). Either way, he must notify his observers (if any) when something interesting happens. The good thing is that he actually doesn’t know the true faces of his observers. He only has a list of references to instances of some interface. In this list our AchivementsManager is present, because the manager needs to know when the character falls from high height without dying. There is no problem for the AchievementsManager to know about the existence of our character, the problem is when our character knows about the manager. However, that problem is no more thanks to the observer pattern.

Deleting Observers

If you are using C# for a scripting language, or any language with garbage collection you must be wary of memory leaks. What do I mean? Let’s say for example that we have an observer (UI Screen) that observers some stats of our main character. When the player displays this UI screen, it’s added to the list of observers of the character, so when the stats change the UI screen is notified and updated. Let’s say the player closes this screen. The screen is not visible anymore. However the garbage collector will not delete it. You know why? Because we didn’t remove the observer from the list of observers. Our main character has a reference to the UI screen and the GC will not delete it.

If some observer has done it’s job and is not needed anymore, make sure that not a single observable object has a reference to it. Otherwise the observer won’t be garbage collected.