ALLINSIGHT

Home of the AlmostImplementedException

Singleton Pattern

As preparation for the post about the “Visitor Pattern”, we will make a short trip to the “Creational Patterns” with the “Singleton”.
As the name suggests it means: single, only one. Like the Highlander: There can be only one!
Let’s take a look at the UML diagram.

Singleton (UML)

The singleton assumes responsibility over it’s creation – In most cases at the first access. Therefore we have a private constructor and a private member to keep the instance. Thus the instance is only accessible through the GetInstance method. Furthermore you can specialize a singleton by sub-classes and assign the concrete singleton type at runtime – e.g. if you want different behaviours for different use cases.
A singleton will be used when only one, and exactly one instance of the class is needed. Example for use of singletons are: central logging object, central quere, a unique connection object (e.g. a Connection Pool) or the main form of a gui, or a global settings class. But enough about the advantages. What’s about the disadvantages? Against the definition, it is possible to have more than one singleton – for example in distributed systems, or in parallel processes/threads at creation. The other point is the readability and maintainability of your code. Therefore you should avoid the excessive usage of singleton – especially the use as “global variables”!
In summary: Very cool for logging, global settings, etc. but don’t let them get out of control. Make them thread-safe. No excessive usage – Think about the need!
In our example the chess board will be the singleton and we want to make it accessible from e.g the field without passing it’s reference every single time. At the other hand we want make sure that there is only one chess board. We have two possibilities to implement the singleton: The classical way with assignment of the singleton at first call of GetInstance – or assign the singleton directly at the constructor/member declaration. It’s your choice 😉 I use both, depending on their suitability, because the classical way has the charm of lazy initialization. Here are the implementations of both ways.

Hope you enjoyed this post. We will meet the singleton again in the next post about the “Visitor Pattern”.
This also might be interesting for you: Singleton evil or not?

Share :

, , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *