Monday, 2 December 2013

Factory Method Design Pattern

Key Points :
  • It is creation design pattern
  • Factory is the java class that is encapsulate object creation code
  • Factory class instantiates and return the object based on data provided
  • The different types of objects that are returned from a factory typically are subclasses of a common parent class.
  • Sub class Object creations being defered at Runtime
Example :

Let take an example to understand the factory method design pattern.This is very small and understandable example for factory method design pattern . we have to write a program to display the wishing message like Good Morning,Good Afternoon and Good Evening

We are creating an abstract class which is having an abstract method that can be implement by many sub class.

package com.factorypattern.example;
public abstract class Message {
 public abstract String display();
}

There are three sub classes which is extends to common class names Message and override the display() method.

package com.factorypattern.example;
public class GoodMorning extends Message{
 @Override
 public String display() {
 return "Good Morning";
 }
}
package com.factorypattern.example;
public class GoodAfternoon extends Message{
 @Override
 public String display() {
 return "Good Afternoon";
 }
}
package com.factorypattern.example;
public class GoodEvening extends Message {
 @Override
 public String display() {
 return "Good Evening";
 }
}
 
Now we are creating the Factory class that returns the sub class object based on data provided.

package com.factorypattern.example;
public class MessageFactory {
 public Message getMessage(String str){
 if(str.equals("morning")){ return new GoodMorning();
 } else if(str.equals("afternoon")){ return new GoodAfternoon();
 } else { return new GoodEvening(); }
 }
} 
 
 Now we creates the class that calls the Factory class and pass the data to it.

package com.factorypattern.example;
public class ExecuteFactory {
 public static void main(String[] args) {
 MessageFactory messageFactory = new MessageFactory();
 Message message = messageFactory.getMessage("morning");
 System.out.println(message.display());
 }
}

output : Good Morning

We can also creates the interface instead of abstract class.

Benefits :

Loosing coupling for application
Adding new features for application very easily

Drawback :

The factory has to be used for a family of objects. If the classes doesn’t extend common base class or interface they can not be used in a factory design template.

No comments:

Post a Comment