Design Patterns – Observer

Today I am going to talk about the Observer Pattern. From Wikipedia once again:

“The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.”

In plain old English, the Observer pattern “Defines a dependency between objects so that whenever an object changes its state, all its dependents are notified.”

What does this amount to in the real world. So you know when you sign up to one of those voucher code sites for a specifc type of voucher and you get a notification whenever there is a new voucher type available? That is basically the observer pattern.

In game development a common use case is an Achievement system. It is an example that has been used multiple times, but hey, if it ain’t broke, don’t fix it. In a game, there are Achievements that can be obtained through a variety of different methods. Maybe you are working on Final Fantasy 12 and want to add an achievement that the player gets for shouting they are Captain Basch 1000 times.

If we aren’t clever about how we design this system, we could have a crazy spaghetti like thing that is linked to every part of our code base. This is bad, as the likely hood of you breakign the achievement system if you make a change or vice versa is pretty high. Are you thinking about using a Singleton for this? DON’T. This is a prime example of where not to use a Singleton. We want our nice Achievement system all lumped in one place and we don’t want to tightly couple the system to every single part of the code base. This is where the Observer pattern comes in. The pattern allows one piece of code to announce something has happenned without actually giving a damn who recieves the notification.

Let’s look at some nice C# code. Essentilaly the code can be broken down into two parts. The Subject  and the Observer.

First we will take a look at the subject. The subject holds a list of all the observers interested in getting information ewhen something cool happens. When said something has happenned, it sends a notificaiton to all the observers.

public abstract class Subject
{
    List<IObserver> _observers = new List<Observers>();
    
    public void Notify()
    {
        _observers.ForEach(x => x.OnNotify());
    }

    public void AddObserver(Observer observer)
    {
        _observers.Add(observer);
    }
    public void RemoveObserver(Observer observer)
    {
        _observer.Remove(observer);
    }
}

And to reiterate somewhat, the Observers are the objects interested in doing something when the event happens.

public interface IObserver
{
    void OnNotify();
}

In fact rather than going into the previously mentioned Achievement system, I am going to talk about the “I’m Captian Basch” bit in FF12.

What I want is the NPCs in a certain area to see if they hear it and increase the notoriety. In the below code I have already added the NPCs as Observers from some other system.

public class BaschShouter : Subject
{
...
    private void OnShoutedImBasch()
    { 
        Notify();
    }
...
}

So every time the player refutes Ondore’s lies:

public class NPC : IObserver
{
     public void OnNotify()
     {
          if (NPCIsInEarShotOfPlayer())
          {
              DontBelieveOndoresLies();
          }
     }
}

You also may have some NPCs that are loyal and stop you shouting and you have also registered those:

public class NPCLoyalToOndore : IObserver 
{ 
    public void OnNotify() 
    { 
       if (NPCIsInEarShotOfPlayer())
       {
            ChastisePlayerForLyingAboutMyLeige();
       }
    } 
}

And there we have it. Observer pattern.

Design Patterns – Singleton

Have you player Nier: Automata yet? Do it! It is currently on my shortlist for my Game of the Year. Just not on PC, that version is… well.. broken… and will probably never be fix becasue budgets and game development.

Anyway, I want to talk about the Singleton pattern, a somewhat controversial pattern. Many people say it is overused and have various opinions why they are bad. I am probably going to get labeled as a paraiah for this and say they are not THAT bad, but can be abused. Many people consider it as an “anti-pattern”. On the flip side, I have worked in code bases that have gone to great lengths to avoid them and have actually just made the maintenance of the porject more of a pain than if the singleton pattern was used in a sensible way. In practice, like all design patterns, it is a programming technique that is part of your toolbox and you may find an ideal solution to use it! You may also find terrible ways to use it!

So firstly what IS the Singleton pattern?

Wikipedia tells us that:

“In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.”

In other words it “ensure a class has one instance, and provide a global point of access to it”.

OK, here is a real world example. Here in sunny England we have a Prime Minister. There can only be one PM of the country at a time. Whenever the PM needs to do something, the same PM is called. The PM is a singleton. Yeah, ok, not a great example because politics, but you get the idea. I prefer my Maccys example in the last post…

There are some genuine use cases for a singleton. These can include Input Systems and File Loading systems. These 2 examples in particular are good candidates for singletons as a lot of other areas of the code base will want to access them. They are also likely to maintain their own state. File Systems may be busy loading files asynchrounously and Input Systems are managing the state of the controllers. You don’t really want multiple instances of these guys. What is going to happen if you suddenly have 2 Input Systems? Which one do you pick?

It is worth noting that there can be several different “kinds” of singleton as well.

Ones that exist all the time:

public class Singleton<T> where T : class
    {
        private static readonly T _instance = Activator.CreateInstance(typeof(T)) as T;
        public static T Instance { get { return _instance; } }
    }

Some that are created when needed, saving memory if they are never called.

public abstract class LazySingleton<T> where T : class
{
       private static T _instance = null;
       public static T Instance
       {
            get
            {
              if (_instance == null)
              { 
                    _instance = Activator.CreateInstance(typeof(T)) as T;
              } 
              return _instance; 
            }
      }
}

And some explicit to working with Unity that I won’t go into here.

Like all design patterns, the Singleton is good at solving a certain type of problem.

However, as I mentioned they can cause issues. Yes, Singletons provide a nice point of access to a point in you program so you don’t have to pass refs to everything. However, the main porblem in my opinion is they encourage coupling. Now while not all coupling is bad, it can be from an architectural standpoint. For example, say you have a racing game that you have a beautifully architected so it is all loosely coupled. Inside is Audio Manager that has been made a Singleton. A brand new, fresh-out-of-uni grad joins your project and is given the task to make the cars make a horrible, expensive-souding crunch noise play when the cars collide. What does he do? He goes into the physics code and couples the audio to the physics. Architecture broken.

There are a lot of other reasons not to Singleton. If you used all the information provided when you type into google “why are singletons bad” you could write a whole book on the subject. They may have emerged from a book that was written in 1994, may not be thread safe, they can be misused, etc. But at the end of the day, they are a tool to solve certain problems. And to be honest, in the right scenarios they can be pretty good tools. Although it is nice to have a really beautiful, loosely coupled and architected system, this could be the most complex thing in the world you have to deal with and when it comes to actually getting stuff done, it could be a massive pain. Yes, bugs maybe harder to track down becasue of Singleton state, but hang on, if you architect them correctly they can perform a single point of contact for a certain system. Which if you find the bug is in that system, it is potentially easier to find?

Basically, although you will read every other book saying Singletons are bad, if you are smart with them, they can actually be pretty powerful tools. Also most of the arguments you will see are around OOP, and in games, there are reasons in 2017 not to go down the OOP route. I have also seen in my time “clever” OOP design make everything a hell of a lot more complicated to jsut get stuff done. In summary, like all patterns, Singletons are a tool, theya re good for some scenarios, but don;t right them off.

Until next time!

Design Patterns – The Command Pattern

Again, I am not gonna bother trying to find relevant images for this stuff, so have a nice picture of Wipeout Omega Collection that came out last week. Wipeout is my favourite Anti-Grav racer, sorry F-zero, I grew up with the PlayStation 🙂 .

Anyway, lets have a look at the Command Pattern. I have been reading up on the Command Pattern recently, and it seems pretty popular with it being Robert Nystrom’s favorite pattern! (He is the author of Game Programming Patterns. It is a good book, I would recommend it! He also has it all up for free on his website).

Unfortunately, as Mr Nystrom says, the Command pattern as an annoyingly obtuse description:

“Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.”

Seriously, it would be nice not to here a technical definition of something in a language other than nerd once in a while. In English, Commands are an object-oriented replacement for callbacks. It allows you to encapsulate actions into objects with the main objective being to provide the means to decouple the client from receiver.

Does that kind of make sense? OK, well either way let’s look at an example or two.

In the real world, say you were at Maccy D’s after a night out. You want a large portion of C-Nugz with a Cheezy B for the road (or a Large Chicken Nugget meal with an extra cheeseburger. They are only like an extra quid, so why the hell not?). Let’s say it is old school maccys where there is someone taking your order. You (the Client) ask the guy (the Invoker) for your meal of goodness (the Command). The guy plugs that in and a request is made to the Chef(the Receiver) to create it. Do you see what is going on? The Client gives an Invoker a Command that is then past on to the Reciever that actually knows how to deal with the Command.

Let’s look at it in more game dev terminology. I am going to write some C#, because C# is awesome (C++ is alright too, but C# is easier to just get stuff done 😉 )

Let’s say I am making that really popular Side Scrolling Shooter on Vita known as Storm Ship Shiro. We will likely want to put in a way to remap the controls (something I admittedly didn’t do back in the day…). First I am going to make an abstract class called Command.

public abstract class Command
{
    public abstract void Execute()
}

The main part of the game I may want to remap is Firing the main Weapon. Firing the Weapon is a Command so what do you think I am gonna do? Make a class that inherits from this Command.

public sealed class FireWeapon : Command
{
    public override void Execute()
    {
        //Fire logic goes here
    }
}

Cool so we have our command, what is our Client. Well in this case that is more “conceptual”. You could say our player is the Client. Our Invoker however could be our Input System that has the following code:

Command onButtonA;
public void SetButtonACommand(Command command)
{
    onButtonA = command;
}
//A load of code...

if (Input.GetButtonDown(Button.A))
{
    onButtonA.Execute();
}

If we plug in the following:

InputManager.SetButtonACommand(_playerShip.FireWeapon);

Then we have mapped that to Button A.

In this case the Client is the player, the Invoker is the Input System, Firing the Weapon is the Command and the Reciever is the Player’s ship.

If we check our simplified definition:

“Allows you to encapsulate actions in objects with the key idea being to provide the means to decouple client from reciever”

That is exactly what this Input system is doing.

Cool huh?

There are many other examples of how the Command pattern is used, one is Undoing and Redoing actions. Say you had a Tactics style game where you could see the outcome of your move. You move your character and then tell him to attack. You didn’t like that last action you performed. So you decided to return to just the move and then use an Item. The client here is still player but the Invoker is a core game system that has a load of commands for every action a character can do. The receiver then is the character themselves.

The command pattern is pretty cool, have a look at it!