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
              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))

If we plug in the following:


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!

Design Patterns – Intro

Image result for persona 5

As usual, I couldn’t find a decent picture, so I just put up one of Persona 5. I am still playing it, it is really good. Pick it up!

Recently I have been going through all my knowledge and figuring out where my core knowledge gaps are. After doing a few tests, etc, I found one of these was design patterns. I have used them a lot in the past, but there are still a few that I am not super comfortable with, so as with most things, I thought I would revise them by doing blog posts about them. Makes sense right?

Firstly, why are design patterns important?

I have worked with a number of code bases, both good and bad. Some code is built in an extremely nice way, other bits are hacked together willy nilly just writing code and not really thinking about the architecture to solve the problem. I myself have done both at some point or another, for a variety of reasons that I may go into in a later post. Design patterns CAN help with this, but there are some caveats.

Let me go on a bit of a tangent a bit. In 2017, games are often not a fire and forget bit of software. They are living breathing things which we can later update and make better. We have platforms like Steam, PS4, Xbox One and Switch which allow us to patch our games unlike the days of PS1 and PS2. We also have games that require lots of Live Operations and will require us to revisit code to add features or extend existing ones. We will essentially need to make changes and design patterns are one way that can kind of help us write code in anticipation that we are one day going to have to make these changes. They are no silver bullet, but they can help towards this.

But hang on, why is that the case? Well let’s look at the definition or what a design pattern is.

According to Wikipedia – “a software design pattern is a general reusable solution to a commonly occurring problem within a give context in software design.”

Let’s say you get to a code base ¬†and you need to make a change to a feature that you are not super familiar with. This feature is meaty, but luckily as you peruse through it you can see some familiar patterns and the classes, etc seem to be named in familiar ways. You realize that someone has used a design pattern and you can use your knowledge of the design pattern to get stuck in. The amount of time taken in understanding the code has decreased and the amount of time needed to make your change. This is because they are defined as reusable solutions to commonly occurring¬†problems. Yes you will still need to learn what the code is actually doing, but¬†as it is a solution to a problem that has cropped up before, their usage is communicating to you what the goal of this system was and it’s intention. Similarly, as it is a familiar solution to a commonly solved problem, the code is likely to be more readable and thus also easier to maintain, which is good as someone else comes back and revisits it again.

You have been given a feature on the game to do. It is pretty big and you need to architect a system. You come up with a system that fits within a design pattern. By doing this, you can easily explain to other developers how exactly you are going to implement a feature. You can talk about how you are going to use a Factory to handle all your object creation, or an Observer to handle when to trigger an event. It gives developers a common vocabulary to talk about and can be used as a good starting point in a discussion whether or not that it is a good way of implementing the solution to the problem you are trying to solve.

Here is a final example. Say you are writing a feature, and it sounds very similar to something that already exists. You look up the code for this old feature and find the underlying system is written in a nice reusable manner as it followed a specific design pattern. This is awesome as it means you won;t have to write a tonne of common code to solve your issue.

So let’s look at the key points at why Design Patterns are important:

  • They make code more¬†readable
  • They make code easier to maintain
  • They can make it easier to communicate your intentions to other developers
  • They allow for code re-use and less code

Sounds great, right. There are a fair few good reasons why you should use a design pattern, but there are caveats. Like I mentioned briefly before, they are not the silver bullet. And can cause problems.

  • They can make the code more complex – some of them patterns use a lot of indirection and less experienced members of your team may have a harder time following them
  • You need to know when to use them –¬†There are always dangers of using the wrong pattern and also using them just for the sake of it. Regardless of how senior you are, when developing a big feature and want to use a design pattern, chat it through with another developer. Otherwise it will make life harder rather than easier
  • Some can hurt game performance –¬†patterns can make your code more flexible and easier to reuse, but this can in some cases come with a cost to performance. They can rely on features that have a greater runtime cost. There needs to be a balance here. Although you are writing more flexible and potentially easier to understand code,a re you shooting yourself in the foot when it comes to performance?
  • They can be abused –¬†Google the Singleton pattern and you will find a lot of discussion around its abuse.
  • You can code yourself into a corner –¬†This is a very specific case I have found when it comes to dealing with live games. Originally, you used a certain design pattern to create a feature based on the design. However the game is out in the wild and analytics are revealing that players are having a hard time with it, don’t enjoy it or it just doesn’t work as a concept. The game is a living breathing thing and you have to adapt it. The change you have been given is not that big conceptually, so you go to the code base. However, because you built the code in such a specific way, it is actually going to take a long time to unpick parts of it and put in this change. You essentially coded yourself into a corner.

So yeah, Pros and Cons. The main points here are:

  • Design patterns are powerful and can help make your code better,¬†when thinking about using¬†them, research them and discuss your solution with others to evaluate the pros and cons.
  • Don’t be the “Small Boy with a design¬†pattern” and use them for the sake of it

Awesome! Next we will be looking at some of the Command Pattern!