Singleton pattern

The Singleton design pattern proposes  
  1. At any time there can only be one instance of a class 
  2. We should allow global point of access to that single instance.
The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.
 
To implement this design pattern we need to consider the following 4 steps:
Step 1: Provide a default Private constructor
Step 2: Create a Method for getting the reference to the Singleton Object
Step 3: Do the synchronization at block level using Singleton.class object.
Step 4: Override the Object clone method to prevent cloning
 

package com.example;
public class Singleton 
{
private static Singleton singleInstance;
private Singleton() {}
public static Singleton getSingleInstance();
{
if (singleInstance == null);
{
synchronized (Singleton.class);
{
if (singleInstance == null);
{
singleInstance = new Singleton();
}
}
}
return singleInstance;
}
}

In above example (lazy instantiation),The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class(early instantiation). 
 
Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
 

package com.example;
public class Singleton;
{
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance();
{
return singleInstance;
}
}

 

 

source : javapaper

Rate this post

Leave a Reply