The Singleton Pattern

The Singleton is a design pattern very useful and very simple as well.
This is the definition provided by Gang of Four :

” Ensure a class has only one instance and provide a global point of access to it.”

Let’s start with the conceptual aspects using Java as language and finally we’ll provide solutions for C# and Unity as well.

Main features

A Singleton class has three main features :

  1. There must be only one istance of the class, stored in a static attribute
  2. A private constructor
  3. A static method that provides access to the class instance

The Singetlon can have Lazy Initialization or Early Initialization

Early Initialization

The object is initialized as the class is loaded.
This is a naif solution. Really easy but with some drawbacks:

  • your Singelton class cannot have dependencies to other Beans or Class when inited
  • your Singleton class is instantiated even if you will never use it. Memory for nothing.

Lazy Initialization

The object is initialized the first time used, no memory is occupied in vain.
This is the choice when you have to inject dependencies.

Take a look at the implementation with Java EE 6 annotation.

Multithreading application

In multithreading application  we must guarantee that only one instance of the Singleton exists.
To get this we use the Double-Checked Locking Pattern.

There are two particular cases that is good to keep in mind

Classloaders

Just be careful if you have two different classloaders.
A class with the same name and package,  loaded by two different classloaders, has two instances in memory.
So in that case we have two instances of the same Singleton.

Serialization

If Singleton implements java.io.Serializable and class is serialized and deserialized more time, we have multiple instances.
To avoid this problem just implement readSolve() method of Serializable interface.

 

Singleton vs Static class

It is worthwhile to analyze in deep the differences between Singleton and static class:

Singleton :

  • it can be used Polymorphically, implementig interface or extending class
  • it can be passed as parameter
  • it can be serialized
  • it can be lazily initialized
  • you can clone Singleton object
  • it is easy to mock for testing
  • used by IoC framework like Spring

Static class :

  • Static classes are not the right place to store State ( in terms of OOP)
  • living in Stack memory it has better performance if for example you have to perform Math operations ( Java static classes are bounded at compile time)

So if you have simple procedural method with no need to store object state, use static class.
Otherwise Singleton is a more power and flexible solution.

 

C# implementation

And now the code for C#. You can find it on Implementing Singleton in c#

Early Initialization

Lazy Initialization

Multithreading

You can find a very good article with other C# implementations in

Implementing the Singleton Pattern in C#

Unity Singleton

The Singelton pattern gives you many advantages in Unity :

  • you can access properties and methods of Singelton class without having a linked reference to the object (set in the editor) or calling GameObject.Find().
    Just call :

  • you can easily create and access a class that stays in memory through all application life

The Singelton implementation for Unity is well described on Unity Wiki.
Our solution is the same with only few differences.

The main difference is the presence of the virtual methods Init and InitCoroutine for lazy initialization. You can call this method in the Start method of MonoBehaviour, or you can call it at the exact time and place you need.

Moreover we have deleted

because often you may want to have Singleton for only one scene.
In case  you can add this line into the Init method of your Singleton.

We have introduced another important difference ( suggested by fholm on reddit ) , deleting the

and the lock on it.
That’s because a MonoBehaviour singleton can be inited or used only by the main unity thread.

Conclusions

Our excursion through the Singleton pattern has come to the end.
We hope it has been worthwhile and we are glad to receive your impressions or suggestions.
Have a good programming !

5 Comments

  1. rox
    Jul 21, 2014 @ 09:10:49

    One of the goal of this post is to share information and to improve our knowledge, especially for C# and Unity.
    For this reason we want to thanks everyone who will contribute to this and any other post, reporting errors or suggesting improvements.

    Reply

  2. rox
    Jul 21, 2014 @ 09:13:23

    Reply

  3. Taylor Kems
    Aug 23, 2014 @ 02:45:03

    I think you forgot the after the “MonoSingleton” declaration.

    Reply

    • Taylor Kems
      Aug 23, 2014 @ 02:46:32

      Ok, you didn’t forget it. It looks like your site might be parsing the as HTML.

      Reply

      • Taylor Kems
        Aug 23, 2014 @ 02:47:31

        Lol ok. All angle brackets are getting parsed…

        Reply

Leave a Reply