Showing posts with label DesignPatterns. Show all posts
Showing posts with label DesignPatterns. Show all posts

Tuesday, 15 January 2019

SOLID Design Principles

SOLID Stands for


  • S means SRP(Single Responsibility Principle)
  • O means OCP(Open-Closed  Principle)
  • L means LSP(Liksov Substitution Principle)
  • I means ISP(Interface Segregation Principle)
  • D means DIP(Dependency Inversion Principle)

SRP(Single Responsibility Principle)

The Single Responsibility Principle (SRP) states that a class must have one single reason to change.

OCP(Open-Closed  Principle)

The Open-Closed Principle (OCP) states that a class should be available for extension, but not for modification.

LSP(Liskov Substitution Principle)


The Liskov Substitution Principle (LSP) states that  a child class should behave as the parent in classes which only knows about the parent class.

ISP(Interface Segregation Principle)

The Interface Segregation Principle (ISP) states that a class should depend upon only on things it actually needs or uses.

DIP(Dependency Inversion Principle)

The Dependency Inversion Principle (DIP) states that a class must not be concerned regarding where is gets its data from.


Happy Reading!

Thanks for reading my tutorials. Please help me in delivering right content with useful comments. 

Wednesday, 26 August 2015

Complete Singleton Pattern in Java Tutorial

I'm going to deliver a Complete Singleton Design Pattern in Java Tutorial here. 

What is  Singleton Design Pattern?

In Java, Singleton Pattern ensures that there is one and only one instance of a class is created in the JVM (Java Virtual Machine).

It is one of the Creational Design Patterns. 

Use-cases of Singleton Pattern:


  • Logging
  • Caching
  • Configuration File
  • Thread Pool
  • Connection Pool
  • Database Driver Object
It is also used with other Java SE Design Patterns:
  • Abstract Factory Pattern
  • Factory Pattern
  • Builder Pattern
  • Prototype Pattern
  • Facade Pattern

It is also used with some Java EE Design Patterns:

  • Service Locator Pattern


Singleton Pattern Class Diagram:



Singleton Pattern Approach:

  • Static instance of the singleton class.
  • Private constructor.
  • Static utility method to create and access the instance globally.


Singleton Pattern Implementation:

1. Eager Initialization Approach:


public class MySingleton {
private static final MySingleton instance = new MySingleton();
private MySingleton(){
}
public static MySingleton getInstance(){
return instance;
}

}

Drawbacks of Eager Initialization:

  • Does not support Lazy-Initialization
  • Does not support Exception Handling
  • No Thread-Safety that means cannot use in Multi-Threaded Environment.
  • Because of Eager Initialization, it creates objects without any Client request or Client does needed it.
  • Unnecessary waste of memory for unwanted objects.
  • Breakage by Serialization
  • Breakage by Cloning
  • Breakage by Java Reflection

2. Lazy Initialization Approach:

public class MySingleton {
private static final MySingleton instance = null;
private MySingleton(){
}
public static MySingleton getInstance(){
                if( instance == null){
                       instance = new MySingleton();
                }
return instance;
}

}

Advantages of Lazy Initialization:

  • Supports Lazy-Initialization
  • Support Exception Handling
  • It creates objects on demand from Clients
  • No wastage of memory


Drawbacks of Lazy Initialization:
  • No Thread-Safety that means cannot use in Multi-Threaded Environment.
  • Breakage by Serialization
  • Breakage by Cloning
  • Breakage by Java Reflection
3. Double-Checked Locking Approach:

public class MySingleton {
private static final MySingleton instance = null;
private MySingleton(){
}
public static MySingleton getInstance(){
                if( instance == null){
                       syncronized(MySingleton.class){
                                if( instance == null){
                                        instance = new MySingleton();
                                 }
                       }
                }
return instance;
}

}

Advantages of Double Checked Locking:

  • Supports Lazy-Initialization
  • Support Exception Handling
  • It creates objects on demand from Clients
  • No wastage of memory
  • Works well in Multi-Threaded Environment
Drawbacks of Double Checked Locking:
  • Breakage by Serialization
  • Breakage by Cloning
  • Breakage by Java Reflection
4. Bill Pugh Singleton Approach:

public class MySingleton {

private MySingleton(){
}

        private static class MySingletonHelper{
           private static final MySingleton instance = new MySingleton(); 
        }
public static MySingleton getInstance(){
return MySingletonHelper.instance;
}

}

Advantages of Bill Pugh Singleton:

  • Supports Lazy-Initialization
  • Support Exception Handling
  • It creates objects on demand from Clients
  • No wastage of memory
  • Works well in Multi-Threaded Environment
  • Not required external Synchronization.
Drawbacks of Double Checked Locking:
  • Breakage by Serialization
  • Breakage by Cloning
  • Breakage by Java Reflection
5. Enum Approach:

Why should we use Enum as Singleton in Java?

a) It are very easy to write Singleton Objects using Enums.
b) Enum are globally accessible
c) By Default, only one instance of Enum is created in JVM.
d) Enums are Thread-Safe by default (No need external synchronization) and guaranteed by JVM
e) Enum Singletons handle Serialization and Deserialization  by themselves and guaranteed by JVM

Example:

public enum MyEnumSingleton{
 INSTANCE;
}

Drawback of Enum Singleton:

a) It does NOT support Lazy-Initialization.


How to solve Serialization Problems with Singleton Pattern:

If we don't follow the following approach, Serialization  will breaks Singleton Pattern Implementation.

Implement readResolve() method as shown below:


public class MySingleton implements Serializable{


      private static final long serialVersionUID = 1L;

private static final MySingleton instance = null;
private MySingleton(){
}

public static MySingleton getInstance(){
                if( instance == null){
                       instance = new MySingleton();
                }
return instance;
}

        protected Object readResolve() throws ObjectStreamException
        {
                return getInstance();
        }

        protected Object writeReplace() throws ObjectStreamException
        {
                return getInstance();
        }


}


We need to implement readResolve() method because during Serialization process readObject() is used to create instance and it return new instance every time. 

However, by using readResolve() method we can replace it with original Singleton instance. 

How to solve Reflection Breakage with Singleton Pattern?

Check and Throw exception in Constructor as shown below:

public class MySingleton implements Serializable{

    private static final long serialVersionUID = 1L;

private static final MySingleton instance = null;
private MySingleton(){
   if( MySingleton.instance != null ) {
             throw new RuntimeException("Invalid" );
            }
}

        public static MySingleton getInstance(){
          if( instance == null){
                 syncronized(MySingleton.class){
                     if( instance == null){
                                 instance = new MySingleton();
                     }
                 }
          }
  return instance;
        }

        protected Object readResolve() throws ObjectStreamException
        {
                return getInstance();
        }

        protected Object writeReplace() throws ObjectStreamException
        {
                return getInstance();
        }


}

Singleton Pattern with "volatile" modifier:

The "volatile" modifier gives latest up-to-date value always in a most accurate manner in Multi-Threaded Environment.

 private static volatile final MySingleton instance = null;

How to solve clone() Breakage with Singleton Pattern?

Implement clone() as shown below.

public class MySingleton implements Serializable{

    private static volatile final long serialVersionUID = 1L;

    private static final MySingleton instance = null;
    private MySingleton(){
if( MySingleton.instance != null ) {
             throw new RuntimeException("Reflection is not allowed." );
        }
    }

   public static MySingleton getInstance(){
          if( instance == null){
                 syncronized(MySingleton.class){
                     if( instance == null){
                                 instance = new MySingleton();
                     }
                 }
          }
return instance;
   }

   @Override
    protected Object readResolve() throws ObjectStreamException
    {
return getInstance();
    }

    @Override
    protected Object writeReplace() throws ObjectStreamException
    {
return getInstance();
    }

   @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Cloning is not allowed"); 
    }


}

This final version is the best Singleton Design Pattern approach.

Singleton Pattern Vs Static Class?



  • When our class does not have any state, then use Static class.
  • When our class have some state, then don't use Static class.
  • Static class provides better performance than Singleton class because it is evaluated at compile time.
  • Static class is not flexible because it does not support overriding. We cannot override static methods in Java.
  • Single class can support Inheritance and Polymorphism where Static class cannot.
  • Static classes are always eagerly loaded where as Singletons can be implemented using Lazy loading approach.
  • Testing Static class is bit tough than Singleton class. But both are bit tough to test.
  • We can clone Singleton class object where as Static class does not support this.
  • Singleton objects store in Heap Memory where as Static class objects store in Stack Memory.


Tuesday, 21 October 2014

UI Design Patterns: MVC,MVP,MVVM

UI Design Patterns


  • MVC
  • MVP
  • MVVM
MVC Pattern

MVC Stands for

  • Model
  • View
  • Controller

















Here Model and View are different components. They have very less coupling.
When Client send a Request to the application, it first reaches the Controller component. The Controller is the responsible to hand this request.

Struts, Spring etc Frameworks follow this MVC pattern.

The Controller will take other components help to find the next View and also its data with Model. 

The Controller will bind this Model data into View and send this View as a Response to the Client.

MVP Pattern

MVP Stands for

  • Model
  • View
  • Presenter




















Here Model and View have tightly coupling.

In case of MVP, View Component binds to the Model directly through Data Binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. 
The Presenter will also contain logic for pressing a button, navigation. It means that we have to write some code in View in order register to the Presenter.

MVVM Pattern

MVVM Stands for

  • Model
  • View
  • ViewModel
Model and View acts similarly as in MVC Design Pattern.
Model contains data. View is used to represent UI to the user.
ViewModel sits between View and Model components to separate Model data binding to the View components  and take care of all UI Actions.

One of popular Java Script Frameworks i.e. Angular JS follows this MVVM pattern.


















Advantages of MVVM Pattern:

As we are separating binding of Model data to View component to a separate component and single place, we will get the following benefits
  • Easy to develop
  • Easy to test
  • Easy to extend
  • Easy to maintain

Friday, 31 May 2013

Null Object Pattern

Null Object Pattern

What is the category of Null Object Pattern?
Null Object Design Pattern comes under Behavioral patterns

What is Null Object Pattern?
Null Object Design Pattern is used to represent "Do Nothing" behavior.
It provides a Null Object as a surrogate object for the absence of an object of a given type.

This Null Object do nothing.

In Java SE 8, they have introduced a new class "java.util.Optional" to represent and handle "null" values and to avoid NullPointerExceptions.

Advantages of Null Object Pattern?

  • To avoid null checks and NullPointerExceptions
  • To avoid "if" block to check if that object is null or not