Design Patterns: Singleton
This is a first article of “Design Pattern: Java interpretation” series. Usually I prefer to start any work with a small step. That’s help me to be more confident at the beginning of the way, to successfully achieve a final point. So the post will be dedicated to the Singleton pattern.
The Singleton is one of the creational patterns. This circumstance implies that the pattern applicable to object creation and if to be more precise to control the number of instances. Actually the Singleton permits to create just one instance of the object and no more. Let’s look at classic way of implementation:
public class Superman { private static Superman superman = null; private Superman() {}; public static Superman getInstance() { if (superman == null) superman = new Superman(); return superman; } public void usePower() { System.out.println("Power of SuperMan!"); } }
Here I examine the example of Superman class. For sure there is impossible of multiple Supermans existence in the same time. Superman either is or he doesn’t exist at all. In the code this can be obtained by declaring of private static field of the class, private constructor, and public static method getInstance(), which returns already created object’s instance or creates a new one.
The Singleton is applicable in cases when you need to be sure that object will have just one instance. This can be when you work with a database connection, loggers, some application specific classes (such as Superman) etc.