Singleton
Singleton is a creational design pattern which ensures that a class has only one instance and provides a global point to access it.
Introduction
Sometimes it makes sense in a system to have just only one instance of a certain class, e.g. configuration classes that read properties from a unique file or hardware access to send files to a printer.
Although Singleton seems to be one of the most popular patterns and yet, one of the easiest to implement, there are still certain features of the Java language like concurrency and serialisation, that may create some pitfalls in the pattern implementation, pitfalls we have to cover in order to rest assured that our Singleton instances are really singular.
That said, this post is not going to be “just yet another Singleton quick tutorial”, it is going to show how to safely write a piece of code that properly adheres to the pattern’s contract, both using a regular Java class and an alternative implementation using an enum
.