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
[code language=”java”]
public interface Animal {
void talk();
}
[/code]
Dog.java
[code language=”java”]
public class Dog implements Animal {
@Override
public void talk() {
System.out.println("Woof…");
}
}
[/code]
Cat.java
[code language=”java”]
public class Cat implements Animal {
@Override
public void talk() {
System.out.println("Meow…");
}
}
[/code]
AnimalFactory.java
[code language=”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;
}
}
[/code]
FactoryPattern.java, the getAnimal() is the factory method which creates the object for you according to the string you passed in.
[code language=”java”]
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();
}
}
[/code]
output:
[code language=”text”]
Woof…
Meow…
[/code]
Search within Codexpedia
Search the entire web