Saturday, March 3, 2012

Types of Design patterns in Java

Design patterns are solutions to general problems that software developers face during software development.
This says given a context, this is the best design and solution.

Design Patterns credit goes to Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides (Gang of Four -GoF) 
for coming out with a good collection of Patterns for common Design Problems. 

As per GOF, the Design Patterns are catagorized in 3 parts: Creational, Structural and Behavioral.
    Creational : Talk about Object creation.
    Structural : Talk about Object and Class composition like inheritance and Association.
    Behavioral : Talk about Dynamic Object interaction and distribution of responsibilities.

   Factory: Toy Factory uses Plastic(one super class) with different molds(several sub classes). Creates an instance of several derived classes.
            Factory design pattern is used when do not want to give constructor of a class where object can be created using new keyword.
            It means in Factory Pattern, you are not able to use "new keyword to create objects". 
                Calendar c = Calendar.getInstance();
                Calendar c = Calendar.getInstance(TimeZone);
                Calendar c = Calendar.getInstance(Locale);
                Thread th = Thread.currentThread();
                Class c = Class.forName();
                Runtime rt = Runtime.getRuntime();  

   Abstract Factory Pattern: This is called Factory of Factories. This work around a super factory concept.
   Builder: Separates the construction of a complex object from its representation. There will be overloaded constructors to create objects.
                StringBuffer and StringBuilder.
                StringBuilder sb = new StringBuilder();
                StringBuilder sb = new StringBuilder(int capacity);
                StringBuilder sb = new StringBuilder(String);
                StringBuilder sb = new StringBuilder(String).append(String);
                StringBuilder sb = new StringBuilder(String).append(double);
                StringBuilder sb = new StringBuilder(String).insert(int, int);
   Prototype: A fully initialized instance to be copied or cloned. java.lang.Object#clone() method creates java.lang.Object.
              Again you shouldn't use new keyword to create object. 
   Singleton: President of a country, System class, SessionFactory etc. A class of which only a single instance should exist.
              Config Property file reading/loading.
              DB ConnectionPool object.
                public class SingletonPattern implements Cloneable, Serializable{
                    private volatile static SingletonPattern object=null;
                    private SingletonPattern(){}   //No subclass can be created because of this private default constructor.

                    public static SingletonPattern getInstance(){ //Never put synchronized in method, else other threads will be 
                                                                  //blocked for getting object.
                        if(object==null){                         //Check instance, if there isn't one, enter a synchronized block.
                          synchronized (SingletonPattern.class) {  //We only synchronized the first time through.
                               if(object==null){                   //Once in the block, double check for null and create an instance.   
                                  object=new SingletonPattern();
                        return object;
                    public Object clone() throws CloneNotSupportedException {
                        throw new CloneNotSupportedException("Cloning of this class is not allowed");  
                    private Object readResolve() throws ObjectStreamException {  
                        return getInstance();  

   Adapter: Adapter pattern works as a bridge between two incompatible interfaces. Also called Wrapper patterns.
            Wrapper classes, Arrays.asList() gives List object. Adapter design pattern makes incompatible interfaces 
            work together, without changing them. Ex: you have 2 dimensional array and want an adapter to create a Map
            and automatically load the array as key value pair.
            public static void main(String args[]) {
                Integer[][] squares = { {2, 4}, {3, 9}, {4, 16}}; 
                MapAdapter adapter = new MapAdapter(squares); 
                System.out.println("Adapter map contains: " + adapter); //Adapter map contains: {2=4, 3=9, 4=16}
            class MapAdapter extends AbstractMap { 
                private Map map; 
                public MapAdapter(Object[][] array) { 
                    map = new HashMap(); 
                    for(Object[] mapping : array){ 
                        map.put(mapping[0], mapping[1]); 
                public Set entrySet() { 
                    return map.entrySet(); 
   Decorator: Decorator pattern allows a user to add new functionality to an existing object without altering its structure.
   Facade: Customer care (A single class that represents an entire subsystem). Facade pattern hides the complexities of the system 
           and provides an interface to the client using which the client can access the system. 
   Proxy: Check book leaf, Credit card, Debit card are proxy for Money. An object representing another object. 
          java.rmi.*, the whole API actually.

   Chain of Responsibility: Loan/Leave approval process. A way of passing a request between a chain of objects.
   Command: Command pattern is a data driven design pattern. A request is wrapped under an object as command and passed to 
            invoker object. Invoker object looks for the appropriate object which can handle this command and passes the 
            command to the corresponding object which executes the command.
   Iterator: Next/Previous buttons on TV. Sequentially access the elements of a collection.
             All implementations of java.util.Iterator & java.util.Enumeration.
             public interface Iterator {
                public boolean hasNext();
                public Object next();
            for(Iterator iter = Map.keySet().iterator();  iter.hasNext(); ){
                String name = (String);
                System.out.println("Name : " + name);

   Momento: Memento pattern is used to restore state of an object to the previous state. 
            Implementations of
   Observer: A way of notifying change to a number of classes. Publish/Subscribe JMS API. NotifyMe in e-commerce websites.
   Strategy: In Strategy pattern, we create objects which represent various strategies and a context object whose behavior 
             varies as per its strategy object. The strategy object changes the executing algorithm of the context object.

No comments:

Post a Comment