Factory Pattern
The Factory Pattern is actually a method(factory method) which is used to create objects on the basis of runtime requirements.
Real Life Example:
The factory method is same as the real world factory, It gives the same kind of object with different(based on the input) behavior. For example, There is a machine in a factory which takes wood and paints as input and gives a painted box as the final product. We can create different boxes by just changing the color of paint in the input.
Java Code Example:
Before going to codes, We need to see some key points about factory method implementation.
- We need an interface(Suppose A is an interface).
- Then We need various implementations of A (Suppose B, C, D are implementing A).
- Finally, We need a Factory class with a factory method. The factory method must have the return type of A.
Find the below problem and its solution using the factory method.
Suppose We need to build an application KNOW ABOUT ANIMALS. The application is simple and just take input an animal(like Lion, Deer, Dog ...etc) and display the details and behaviors of the animal.
/**************** The Interface******************/ package test.factory; /** * The interface * Created by chaudharys on 16/4/17. */ public interface Animal { void desc(); } /*********** The Implementations******************/ package test.factory; /** * Created by chaudharys on 16/4/17. */ public class Tiger implements Animal{ public void desc(){ System.out.println("Tiger is big cat."); } } package test.factory; /** * Created by chaudharys on 16/4/17. */ public class Elephant implements Animal { public void desc(){ System.out.println("Elephant has unique body part called trunk."); } } /*************** The Factory *******************/ package test.factory; /** * Created by chaudharys on 16/4/17. */ public class AnimalFactory { //factory method public Animal getAnimal(String animal){ if("Tiger".equalsIgnoreCase(animal)){ return new Tiger(); }else if("Elephant".equalsIgnoreCase(animal)){ return new Elephant(); }else{ return null; } } }
Comments
Post a Comment