Java factory pattern example
Factory pattern is to encapsulate object creation into a method so every time when you creating a new instance of the object you call this method. It standards the object creation and avoids mistakes might have made if you are creating the object yourself.
Animal.java
public interface Animal { void talk(); }
Dog.java
public class Dog implements Animal { @Override public void talk() { System.out.println("Woof..."); } }
Cat.java
public class Cat implements Animal { @Override public void talk() { System.out.println("Meow..."); } }
AnimalFactory.java
public class AnimalFactory { public Animal getAnimal(String animal) { if (animal.isEmpty()) return null; if (animal.equalsIgnoreCase("Dog")) return new Dog(); else if (animal.equalsIgnoreCase("Cat")) return new Cat(); else return null; } }
FactoryPattern.java, the getAnimal() is the factory method which creates the object for you according to the string you passed in.
public class FactoryPattern { public static void main(String[] args) { AnimalFactory animalFactory= new AnimalFactory(); Animal dog = animalFactory.getAnimal("Dog"); dog.talk(); Animal cat = animalFactory.getAnimal("Cat"); cat.talk(); } }
output:
Woof... Meow...
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts