Frequently used Java design patterns

I am writing blogs on design pattern because I couldn't find a site where I can get good information about all the design patterns. So I referred different sites and consolidating design pattern in this blog. Please help me in improving this blog by commenting on it.

Below are three different categories on java design patterns.

Creational Design pattern


  • Singleton Pattern
  • Factory Design Pattern
  • Abstract Factory Design Pattern
  • Builder Pattern
  • Prototype Pattern

Structural Design pattern


  • Adaptor Pattern
  • Bridge Pattern
  • Decorator Pattern
  • Facade Pattern
  • Proxy Pattern
  • Composite Pattern
  • Flyweight Pattern

Behavioral design pattern

  • Chain of Responsibility Pattern
  • Command Pattern
  • Observer Pattern
  • State Pattern
  • Strategy Pattern
  • Template Pattern
  • Visitor Pattern
  • Interpreter Pattern
  • Iterator Pattern
  • Mediator Pattern
  • Momento Pattern
We will not be discussing about all design pattern here. Instead we will discuss about most commonly used pattern.


Singleton Design Pattern

Singleton pattern is a design pattern that allows only one instantiation of a class. It means we can create only one object of that class and that object will be shared across the system. Spring makes most use of singleton pattern by making beans singleton by default.

class Resource{
  private static Resource instance;
  public static Resource getInstance(){
    if ( instance == null ){
      synchronized(Resource.class){
        if ( instance == null ){
          instance = new Resource();
        }
      }/end of synchronized block.
    }
    return instance;
  }
}

The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made private.
We need to be careful while constructing singleton object in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation. This can be achieved by Double-checked locking as shown above.

Difference between Static class and Singleton

  • A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues.
  • Another notable difference is that singleton can extend classes and implement interfaces, while a static class cannot (it can extend classes, but it does not inherit their instance members). Singleton follows OOPS while Static class doesn't.
  • Static class provides better performance than Singleton pattern, because static methods are bonded on compile time.
  • Static classes are hard to mock and consequently hard to test than Singletons, which are pretty easy to mock and thus easy to test. It’s easier to write JUnit test for Singleton than static classes.
Factory Design Pattern
Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.
At times, we had a requirement to get similar type of objects at run time. We can use Factory pattern in these scenarios.

public static StoreRecommendation findStoreRecommendation(
            final String storeCode) {
        StoreRecommendation storeRecommendation = null;
        try {
            storeRecommendation = (StoreRecommendation) Class.forName(
                    BASECLASS + "_" + StringUtils.upperCase(storeCode)
                            ).newInstance();
        } catch (final ClassNotFoundException e) {
            logger.error("Error: Creating store specific recommendation - "
                    + e.getMessage());
        } catch (final Exception e) {
            logger.error("Error: RuntimeException - " + e.getMessage());
            throw new RuntimeException(e);
        }
        return storeRecommendation;
    }

In above example, StoreRecommendation is the interface which every StoreRecommendation class should be implementing. Here we are using reflection to create the instance since number of stores are more. In case you don’t want to use reflection and number of objects are limited, you can create the objects based on conditions. You might have seen some of the sites where Factory is returning different greeting based on if person is male or female.

Abstract Factory Design Pattern
Abstract Factory provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. It is similar to factory pattern except that it return factory instead of concrete class.

public static RecommendationFactory findRecommendationFactory(
            final String storeCode) {
        RecommendationFactory recommendedfactory = null;
        try {
            recommendedfactory = (RecommendationFactory) Class.forName(
                    BASECLASS + "_" + StringUtils.upperCase(storeCode)
                            + "Factory").newInstance();
        } catch (final ClassNotFoundException e) {
            logger.error ("Error: Creating store specific factory -”
                    + e.getMessage ());
        } catch (final Exception e) {
            logger.error ("Error: RuntimeException - " + e.getMessage ());
            throw new RuntimeException(e);
        }
        return recommendedfactory;
    }

e.g. in above example, based on a store code passed, it can return store specific factory. Each store will have its own factory which in turn can return different recommendations based on passed algorithms.

Builder Design Pattern

Purpose of this pattern is to build complex objects from simple ones step-by-step. It separates the construction of complex objects from their representation so that different implementations of these steps can construct different representations of objects.

There is a good example of builder design pattern given in http://en.wikipedia.org/wiki/Builder_pattern. So we will not repeat it. Another good example can be found at http://www.allapplabs.com/java_design_patterns/builder_pattern.htm

Prototype Design Pattern

Prototype means cloning. If creation of object is expensive, then we clone the object instead of creating a new object.

The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype. Class needs to implement cloneable interface.

I found one good non software example mentioned at http://javapapers.com/design-patterns/prototype-pattern/

Adapter Design Pattern

Adapter design pattern is used when we have two unrelated interfaces which can't work together.e.g. you might have seen that some of the electronic instruments bought from US doesn't work in India.This is because we use 220V in India while 110V is used in US. So in order for them to work in India, we use voltage adapter which converts 220V to 110V. Same concept is used in software when we have two different interfaces which needs to interact. This is mainly used in case of legacy implementation.

Solution to this problem is to write a new implementation using inheritance or composition.

Bridge Design Pattern

Bridge pattern implies that interface should be abstracted from its implementation. It says that implementation should separated out from interfaces as implementation might change during course of time. It is heavily used in Spring where we program in term of interfaces.

Decorator Design Pattern

Decorator pattern adds behavior or responsibilities to an individual object without affecting behavior of other objects from the same class. In other words, we can add behavior or feature to an object at run time. In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.

Below is the interface of our example Product. We will be writing decorator on top of that.

public interface Product{
  public BigDecimal getPrice();
}

Below class is concrete implementation of above interface. We will be writing decorator on top of this class.

public class BaseRecommendedProduct implements Product{

private BigDecimal basePrice;

public BigDecimal getPrice(){
return basePrice;
}
}

Below class is decorator class and core of decorator design pattern.

abstract class BaseRecommendedProductDecorator implements Product{

private BigDecimal storeSpecificPrice;

public BigDecimal getPrice(){
return storeSpecificPrice;
}
}

Below class is our concrete decorator class. Here we are invoking price of abstract class and adding(decorating) behavior to that.

public class StoreSpecificRecommendedProductDecorator extends BaseRecommendedProductDecorator{
public BigDecimal getPrice(){
return super.getPrice() + //Add some behavior;
}
}


Facade Design Pattern

Facade means face of the building. What it means is to hide the complexities of the class by exposing a simple interface.One of the best example of its implementation in java is  "java.sql.Connection" interface. Its implementation is left to the vendor for implementation. One of the example in real life is that we have waiters in restaurant. We order food through them and they work as interface. They hide the complexity of how food items are being prepared. Another example is how car and computer works. We don't have to bother about complexity of how car or computer is built.

Proxy Design Pattern

Sometime creation of object is so expensive that we avoid till we actually need it. Proxy design pattern allows you to provide an interface to other objects by creating a wrapper class as the proxy. For example if we need to use only a few methods of some costly objects we'll initialize those objects when we need them entirely. Until that point we can use some light objects exposing the same interface as the heavy objects. These light objects are called proxies and they will instantiate those heavy objects when they are really need and by then we'll use some light objects instead.

Example is that if we need to pass/share images with someone, then we can host them to a place and share url/link to those images. Images will be fetched only when someone actually clicks on the link. Another good example in software is web services. In web services, we create proxy of actual service at client side. These proxies actually invokes web services when user needs it.

Chain of Responsibility Design Pattern

Chain Of Responsibility design pattern avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request.  This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. In software, we have multiple interceptors and filters which handle the request before it passes to actual object handling the request. If we talk in term of ESB, we have multiple transformers which can handle the request before it is passed to components.

Another example can be Logger class. Each logging handler acts as the processing object. Each handler decides if any action is to be taken at this log level and then passes the message on to the next logging handler.

Strategy Design Pattern

Strategy Design Pattern is a design pattern where an algorithm's behavior can be selected at run time.

Strategy pattern (also known as the policy pattern) is a software design pattern, whereby an algorithm's behavior can be selected at runtime. The definition of Strategy provided in the original Gang of Four book on Design Patterns states "Defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior."

The Strategy pattern is to be used where you want to choose the algorithm to use at runtime. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression.

One of the good example is mentioned at the Wikipedia.

/** The classes that implement a concrete strategy should implement this.

* The Context class uses this to call the concrete strategy. */

interface Strategy {

    int execute(int a, int b); 

}

 

/** Implements the algorithm using the strategy interface */

class Add implements Strategy {

    public int execute(int a, int b) {

        System.out.println("Called Add's execute()");

        return a + b;  // Do an addition with a and b

    }

}

 

class Subtract implements Strategy {

    public int execute(int a, int b) {

        System.out.println("Called Subtract's execute()");

        return a - b;  // Do a subtraction with a and b

    }

}

 

class Multiply implements Strategy {

    public int execute(int a, int b) {

        System.out.println("Called Multiply's execute()");

        return a * b;   // Do a multiplication with a and b

    }    

}

 

// Configured with a ConcreteStrategy object and maintains

// a reference to a Strategy object 

class Context {

    private Strategy strategy;

 

    public Context(Strategy strategy) {

        this.strategy = strategy;

    }

 

    public int executeStrategy(int a, int b) {

        return this.strategy.execute(a, b);

    }

}

 

/** Tests the pattern */

class StrategyExample {

    public static void main(String[] args) {

        Context context;

         // Three contexts following different strategies

        context = new Context(new Add());

        int resultA = context.executeStrategy(3,4);

         context = new Context(new Subtract());

        int resultB = context.executeStrategy(3,4);

        context = new Context(new Multiply());

        int resultC = context.executeStrategy(3,4);

        System.out.println("Result A : " + resultA );

        System.out.println("Result B : " + resultB );

        System.out.println("Result C : " + resultC );

    }

}


Source: http://en.wikipedia.org/wiki/Strategy_pattern


State Design Pattern

State design pattern is similar to strategy pattern. Only difference is that instead of algorithm, behavior can be changed at run time.

References

http://en.wikipedia.org/wiki/Singleton_pattern
http://www.javaworld.com/community/node/8425
http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Abstract_factory_pattern
http://www.allapplabs.com
http://javapapers.com/design-patterns
http://java.dzone.com/

Comments

Popular posts from this blog

Brief guide to ecommerce

CQ - How to set replication automatically from Author instance to publisher instance

New age career opportunities in Information Technology after graduation