Singleton Design Patterns

Singleton Design Pattern 
     Singleton design pattern is a creational design pattern that allows you create only one instance for a class.


How are we restricting one instance to be created: 
     By making the constructor private. 

Private constructors: 
    Methods can be made private. Constructor is also a method. Similarly we can also have private constructors. If a constructor is private , it can be accessed only within the class.

Scenarios private constructors are used: 
     • Singleton design pattern
     • Internal chaining of constructors 

Components of a singleton class: 
     • A static instance variable
     • Private constructor 
     • Static factory method 

Two Forms of singleton design pattern: 
     • Early instantiation
     • Lazy instantiation 

Early instantiation: 
 Here we create the instance variable at the time of declaration. So instance is created at the time of class loading.

class A{
private static A obj=new A();//Early, instance will be created at load time
private A(){//private constructor
}
public static A getA(){//static factory method
return obj;
}
}

Lazy instantiation:

Here we create the instance when required within a synchronized block.

class A{
private static A obj;
private A(){
}
public static A getA(){
if (obj == null){
synchronized(Singleton.class){
if (obj == null){
obj = new Singleton();//instance will be created at request time
}
}
}
return obj;
}


 Everything is fine about singleton design patterns?
  •       Whether wondered the realtime scenarios , we use singleton design patterns. 
  •       Why we need to restrict a class with only one instance. 
  •       Ever got all this questions while studying about singleton design pattern. 
  •       The following paragraph gives all the clarifications. 


 We need to restrict a class with one instance for some of the following reasons – 

 Some objects will be used entirely throughout the codeflow. In such cases , the developer might create the  instance numerous time which results in memory heads. To restrict such overheads, a code level   refactoring is provided. This is provided by singleton design pattern.

 For Example:Database objects are used throughout the application. So these kind of objects are created   using singleton design patterns.

 Another reason is that , some values are always unique to the application. They should not be changed. Though the code flow tries to change the value, it should not be changed. To provide that kind of security, this design pattern is used.

 For Example : In Facebook , D.O.B of the account cannot be changes, so this is instantiated using lazy instantiation and used throughout the code flow using singleton design patterns

Comments