Singleton Pattern

July 30, 2013

There are many situations that you need to have just one instance of a kind of objects, Thread pool, Cache, Registry, etc. are some examples of these situations. It is possible you ask a question: “Why do i need pattern for this problem? i can just create one object and make it global static.” .As you will see with using singleton pattern we want to be sure there is just one instance object in all of our system. We need a solution that does not let to the programmer to create more than one instance instead of programmer handle the uniqueness of instance.

Singleton is not very complex, but has some trap points that we explain them in this post. At first let me show you what is Singleton.

In Singleton pattern we don’t let clients to create the object, So our class does not have any public ( and protected is a trap) constructor.

public class SingletonObject {
private SingletonObject() {
}
}

no one out of your class can’t create an instance of your class. Now you need to add a static public method to retrieve your unique object.

It is all of Singleton pattern, now you can be sure that you have just one SingletonObject instance in your application. ‌But there are two issues that you need consider them. First don’t use protected constructor in your singleton class, because everyone can extend your singleton class and add a new public constructor to it :) so you could not restrict programmers to use just one object in their applications, another possible solution is to use final keyword in your class specification.

The other issue is in concurrent environments, When your object does not initialize yet and you have two threads which want to get an instance in the same time, it is possible to have two objects of your singleton, So you need to make your object creation thread safe.

Very easy and simple solution, but if you have high getInstance invocation then your application overhead will become very much. In this situation you can create your object eagerly, it’s not possible everywhere to create your object eagerly but when it is possible you have a good choice. The last solution is to use “Double-checked locking”, In this solution you check you object reference then synchronize for creating object, with this solution the overhead decrease.

But after release 1.5, the best way to implement Singleton pattern is using enum, with this model of implementation you don’t have any concern about the synchronization and the number of objects in your application.

would it be possible to Implement Singleton Design Pattern in a way which we can use it in Derived Classes ?
imagine we have three level of Inherited Classes and All of them have been implemented with Singleton Design Pattern at the End we will have three Different Static GetInstance Method(one Method for each level) …and it’s not a good idea , is it ?
is there anyway ?