Creational Design Pattern : Singleton Design Pattern:

Creational Design Pattern : Designing pattern related to creation of a object or instance of Class.

1) Singleton Design Pattern: It allow to create only objects of a class. So user cant create more then one object of a class. this pattern allows only one instance of a Class in JVM

Advantage: It is useful in caching, reader-writer problem, Creating a object of a class is very expensive... etc

Disadvantage: it cannot use multithreading programming , concurrent processing , thread pool case ...
etc.

There are many ways to create singleton class to create only one instance available in JVM but following is common to all.

# Private Constructor so no other class cannot create instance of Class.
# Private  static variable of class that is only instance of the class.
# Public static method that return the instance of class.

a) Eager Initialization: This one is the easiest way to initialized a singleton class. draw back of  this  is it creates instance at loading time  the class though we might not using.

public class EagerInitialization {

private static final EagerInitialization  instance = new EagerInitialization ();

private EagerInitialization ()
{}

public static EagerInitialization   getinstance()
{
return instance ;
}

public static void main (String a[]){
    //set passed parameter as name
 System.out.println("EagerInitialization instance:  " +  getinstance() );

}
}

Output : EagerInitialization instance:  EagerInitialization@1db9742

Note: To avoid instantiation at load time maens object should be created when client call getinstance.

b) Static Block initialization: It is similar to eager but it create object in a static block that provide Exception handling.

   public class StaticInitialization{

private static  StaticInitialization;// = new StaticInitialization();

private StaticInitialization()
{}
static {

try{

instance = new StaticInitialization();
} catch(Exception e){
//catch the exception at runtime
}

}

public static StaticInitializationgetinstance()
{
return instance ;
}

public static void main (String a[]){
    //set passed parameter as name
 System.out.println("StaticInitializationinstance:  " +  getinstance() );

}
}

Output: StaticInitializationinstance:  StaticInitialization@1db9742
Note: This one have same problem like eager it create object at loading time.

c) Lazy Initialization : it create instance in a global method so it will create when client call.

public class LazyInitialization {

private static  LazyInitialization instance;
private LazyInitialization ()
{}

public static LazyInitialization getinstance()
{
if( instance == null)
{
System.out.println("Creating LazyInitialization instance:  " );
instance = new LazyInitialization ();
}
     return instance ;
}

public static void main (String a[]){
    //set passed parameter as name
 System.out.println("LazyInitialization instance:  " +  getinstance() );

}
}

Note : it will create object but it is safe only for single threaded system in multithreaded process more then one thread can  be in if block so then it can create more then one instance of class.

d) Thread safe singleton: It is same like a lazy but it make global method synchronized, so at a time only one thread can execute method.

public class ThreadSafeInitialization {

private static  ThreadSafeInitialization instance;
private ThreadSafeInitialization ()
{}

public static synchronized  ThreadSafeInitialization getinstance()
{
if( instance == null)
{
System.out.println("Creating ThreadSafeInitialization instance:  " );
instance = new ThreadSafeInitialization ();
}
     return instance ;
}

public static void main (String a[]){
    //set passed parameter as name
  System.out.println("ThreadSafeInitialization instance:  " +  getinstance() );

}
}

Output:Creating ThreadSafeInitialization instance:
ThreadSafeInitialization  instance:  ThreadSafeInitialization @1db9742

Note : It provide the thread safe but every time when we call getinstance which is synchronized, synchronized is a time consuming process. To overcome this overhead a new principle double checked locking in this synchronized method use inside if block

public static synchronized  ThreadSafeInitialization getinstance() {

if( instance == null) {
   synchronized (ThreadSafeInitialization.class ) {
       if( instance == null) {
System.out.println("Creating ThreadSafeInitialization instance:  " );
instance = new ThreadSafeInitialization ();
                }
            }
}
     return instance ;
}


e)Bill Pugh Singleton: it use a inner static class instanceHelper which create the instance of singleton class, and it will create the instance when client call getinstance method and there is required to make synchronization.


 public class BillPughInitialization {

private static  BillPughInitialization instance;
private BillPughInitialization ()
{}

private static class InstanceHelper {

private static final BillPughInitialization  INSTANCE= new BillPughInitialization ();
}
public static BillPughInitialization getinstance()
{
     return InstanceHelper.INSATNCE;
}

public static void main (String a[]){
    //set passed parameter as name
  System.out.println("BillPughInitialization instance:  " +  getinstance() );

}
}  

Note : class InstanceHelper  will load when client call getinstance and that it create instance of singleton class .



f)Enum singleton : use of Enum to design singleton class because  Enum load in a programe once.


 enum Singleton {
    INSTANCE;
   // your class member function
     public void showMessage(String message) {
                System.out.println(message);
     }
}

 public class EnumSingleton  {
    public static void main(String[] args) {

    //You can not create an object of Singleton using new operator
    //Compile Time Error: The constructor Singleton() is not visible
    //Singleton singleton = new Singleton();

    //You can get object of Singleton like this
    Singleton singleton = Singleton .INSTANCE;

     //show the message
     singleton.showMessage("This is a Singleton pattern test");
     //or you can directly call
     Singleton.INSTANCE.showMessage("This is a Singleton pattern test");
   }
}



Comments

Popular posts from this blog

Creational Design Pattern: Factory Design Pattern

Introduction to Java

Design Patterns: The Secret Weapon of Expert Developers