Creational Design Patterns - 3- Factory Method Design Pattern
A factory method Pattern is a creational pattern. it is used to instantiate object from one among a set of classes based on a logic.
Say that we have set of classes which extend common super class or interface .
Now , you will create class with a method which accept argument. this method is our factory method . based on the arguments passed to factory method does logical operations and decide on which sub class to instantiate .
Info : The method newInstance() is the factory method which instantiates the sax parsers based on some predefined logic .
Lets do sample example :
Base Class :
Public interface Pet{ public String speak(); }
First subclass :
Public Class Dog implements Pet{ public String speak(){ return "dog speak."; } }
Second subclass :
Public Class Duck implements Pet{ public String speak(){ return "duck speak."; }
}
Factory Class :
public class PetFactory { public Pet getPet(String petType){ Pet pet = null; } if("dog".equals(petType)) pet = new Dog(); else if("duck".equals(petType)) pet = new Duck(); return pet ; }
Finally use the factory method to init the class :
public class factoryMethodImp{ public static void main(String args[]){ PetFactory petFactory =new PetFactory(); Pet pet = petFactory.getPet(""); System.out.println(pet.speack()); } }
Thanks for Reading ......
See you in other Pattern .