Wednesday, February 29, 2012

Factory Design Pattern

Factory Design Pattern is a creational pattern. This is required when you don't want to give constructor to
create object using new keyword. 

Ex: Toy factory which makes different kind of toys: some in shape of aeroplane, some in shape of a racing car functions.

---------------------------------------
package deepak;
public interface Pet {
  public String speak();
}

package deepak;
public class Cat implements Pet {
    public String speak(){
        return "Meau Meau";
    }
}

package deepak;
public class Dog implements Pet {
    public String speak(){
        return "Bhow Bhow";
    }
}

package deepak;
public class PetFactory {

    public static Pet getPetInstance(String petType) {
        Pet pet = null;
        //Based on logical factory instantiates an object
        if ("Bhow".equals(petType))
            pet = new Dog();
        else if ("Meau".equals(petType))
            pet = new Cat();
        return pet;
    }
    public static void main(String[] args) {
        Pet object = PetFactory.getPetInstance("Bhow");   
        Pet object2 = PetFactory.getPetInstance("Meau");
        
        System.out.println(object);
        System.out.println(object2);
    }
}
--------------Output:----------
deepak.Dog@1650c3
deepak.Cat@1650c4
---------------------END-------------------


No comments:

Post a Comment