The singleton creational pattern is simple and often used. It’s actually used a bit too often so this episode will give you some caution and provide some ideas to modify this pattern when needed.

There are really just 3 parts that make a class a singleton:

  1. Declare all constructors to be private. You may only have one constructor. The main thing is that you don’t leave any overloaded constructors accessible.
  2. Declare a public static method called instance or maybe getInstance that returns a pointer or a reference to an instance of the singleton class. This method will have access to the private constructor and will construct an instance of the singleton class when it’s first called. After that, it will just return the first instance that was created.
  3. Declare a private static data member that’s either a pointer or a reference to the singleton class. I say, or reference, because that may be the way some languages handle pointers. This is the data member that the instance method will use to store the first instance of the singleton.

This pattern is so simple that it’s used a bit too much. The main problem is that it’s actually little better than a global variable. It makes the single instance available throughout your program. For a large program, this can cause problems debugging because the singleton can be accessed and potentially modified from anywhere.

The singleton pattern is useful, just don’t overuse it. The podcast episode also gives you some additional tips for how you might want to modify this pattern.