Singleton is the simplest design pattern (that’s why I wrote an entry about it LOL).
As you can see in the firgure above, a Singleton class consists of:
That’s all. Only one class :)))
This way is a classical Singleton implementation.
public static getInstance(){ if(instance == null){ instance = new Singleton(); } return instance }
Pros:
Cons:
To prevent multi-thread concurrency, let’s take a look at the second way!
The easiest way to prevent multi-thread concurrency is eager initialization.
private Singleton instance = new Singleton(); public static getInstance(){ return instance }
Pros:
Cons:
If you want to resolve all the disadvantages of eager initialization, try this way:
public static getInstance(){ if (instance == null){ synchronized(Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance }
With the synchronized keyword, you can handle multi-thread concurrency case but it will be very costly. That’s why I use the double check locking mechanism( cehck in an unsynchronized block if the object is null and if not to check again and create it in an syncronized block). If we see that the singleton object is already created we just have to return it without using any syncronized block.
Pros:
Cons:
You also can using Enum to implement Singleton:
public enum Singleton { Singleton instance; public void doStuff(){ return instance; } }
Pros:
Cons:
Anything else? Just comment below! :)
Comments powered by Disqus.