Showing posts with label Patterns. Show all posts
Showing posts with label Patterns. Show all posts

Wednesday, December 7, 2011

Patterns: Factory Method

Factory Method

Purpose
  1. Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
  2. Defining a “virtual” constructor.
  3. The new operator considered harmful.

Facotry Method is a Creational Pattern and it deals with Creation of Object without specifying the exact class of object that will be created. Object creation some times requires complex processes not required and it’s not appropriate to write all this code in composing object

Facotry Method design pattern handles this problem by creation of a separate method for creation of object which Subclass can override to provide its own implementation

Essence of Factory Method Pattern is

“Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”


public class TestFactoryMethod {

      public static void main(String[] args) {
            Skin s=SkinFactory.getSkin("web");
            s.printSkin();
      }          
     
}

class SkinFactory{
      public static Skin getSkin(String type){
            if(type!=null && type.equals("web"))
                  return new WebbasedSkin();
            else
                  return new DesktopbasedSkin();
      }
}

interface Skin{
      public void printSkin();
}

class WebbasedSkin implements Skin{
      public void printSkin(){
            System.out.println("I am Web based Skin");
      }
}

class DesktopbasedSkin implements Skin{
      public void printSkin(){
            System.out.println("I am DesktopbasedSkin Skin");
      }
}