#
Factory Method
This tutorial explains to you the design pattern named Factory Method (which is a Creational Pattern).
#
Factory Method - theory
The Factory
(Factory Method
or Virtual Constructor
) Design Pattern is probably the most used design pattern in Java.
In Factory Method pattern, we create object without exposing the creation logic to the client and refer to newly
created object using a common interface. In Factory Method Pattern, we define an interface (or an abstract class)
for creating an object, but let subclasses instantiate the object.
Info
In Factory Method Pattern the object is created using "new" operator, but this is done under the hood.
Info
Creating an object using the Factory Method Pattern is more flexible than creating an object directly.
#
Factory Method - example
Here is the UML Diagram for the Factory Method Design Pattern (for my example):
public interface Animal {
public void setAge(int age);
public String getAge();
}
public class Rabbit implements Animal {
int age;
public Rabbit() {
super();
this.age = 0;
}
@Override
public void setAge(int age) {
this.age = age;
}
@Override
public String getAge() {
return "The RABBIT has "+age+" years old.";
}
}
public class Cow implements Animal {
public Cow() {
super();
this.age = 0;
}
int age;
@Override
public void setAge(int age) {
this.age = age;
}
@Override
public String getAge() {
return "The COW has "+age+" years old.";
}
}
public class Horse implements Animal {
int age;
public Horse() {
super();
this.age = 0;
}
@Override
public void setAge(int age) {
this.age = age;
}
@Override
public String getAge() {
return "The HORSE has "+age+" years old.";
}
}
public class AnimalsFactory {
public Animal getAnimal(String animalType) {
if(animalType == null){
return null;
}
if(animalType.equalsIgnoreCase("RABBIT")){
return new Rabbit();
} else if(animalType.equalsIgnoreCase("COW")){
return new Cow();
} else if(animalType.equalsIgnoreCase("HORSE")){
return new Horse();
}
return null;
}
}
public class FactoryExampleMain {
public static void main(String[] args) {
AnimalsFactory animalsFactory = new AnimalsFactory();
Animal animal1 = animalsFactory.getAnimal("COW");
animal1.setAge(3);
Animal animal2 = animalsFactory.getAnimal("RABBIT");
animal2.setAge(2);
Animal animal3 = animalsFactory.getAnimal("HORSE");
animal3.setAge(4);
System.out.println(animal1.getAge());
System.out.println(animal2.getAge());
System.out.println(animal3.getAge());
}
}
When I run my example, I get the following result: