Friday, March 18, 2016

Design Pattern - 5 Singleton Pattern.



One of the simplest patterns - Singleton patterns - Ensures a class has only one instance and provides gloabl access to it.

Steps:
 Method 1:
1) Create a private constructor.
2) Create a static class variable.
3) Create a public method to return an object of the class.

Class A{
 private static A singleinstance;
 
 private A() {}

 public static A getInstance() {
    if(singleinstance==null) {  //lazy initialization
        singleinstance = new A();
    }
    return singleinstance;
 }
}


Method 2:

Class A{
 private static A singleinstance= new A();
 
 private A() {}

 public static A getInstance() { // Eager initialization
    return singleinstance;
 }
}


Method 3: To avoid synchronization issues while multithreading,
Class A{
 private static A singleinstance= new A();
 
 private A() {}

 public static synchronized A getInstance() { // Ensures only one instance is created while multi threading
     if(singleinstance==null) { 
        singleinstance = new A();
    }
    return singleinstance;
 }
}



Method 4: Double checked locking -
Using synchronized keyword over a method is a performance overhead. So,
Class A{
 private static A singleinstance;
 
 private A() {}

 public static A getInstance() { // Ensures only one instance is created while multi threading
     if(singleinstance==null) { 
       synchronized(this){
    if(singleinstance==null){
           singleinstance = new A();
    }
    }
    return singleinstance;
 }
}


Only for the first time, only then an entry to synchronized block is made.
So, in stead of Method 3, the above approach can be followed in case of multiple threads are used. This way, performance overhead issue can be resolved.

Design Principles so far:

1) Encapsulate what varies
2) Favor composition over inheritance.
3) Program to interfaces, not implementations.
4) Strive for loosely coupled designs between objects that interact.
5) Classes should be open for extension, but closed for modification.

6) Depend on abstractions. Do not depend on concrete classes. 

Used: Logging, Preferences and Registry settings, Thread pools, caches, dialog boxes.

No comments: