Factory Design Pattern. Overview
Overview

The factory pattern is a popular design pattern in Java because it is one of the best way to create an object. The general idea is allowing the user to create objects without exposing the logic behind it. Instead an interface is provided for the user to know what method to be called to create the object.

Photo by Science in HD on Unsplash

Implementation

Interface

Animal.java

public interface Animal {

void species();

}

Implement Interface

Dog.java

public class Dog implements Animal {

@Override

public void species() {

System.out.println("It's a dog.");

}

}

Cat.java

public class Cat implements Animal {

@Override

public void species() {

System.out.println("It's a cat.");

}

}

Bird.java

public class Bird implements Animal {

@Override

public void species() {

System.out.println("It's a bird.");

}

}

Factory

public class AnimalFactory {

// use getAnimal method to get object of type animal

public Animal getAnimal(String animalSpecies){

switch(animalSpecies.toLowerCase()) {

case "dog":

return new Dog();

case "cat:

return new Cat();

case "bird":

return new Bird();

default:

return null;

}

}

}

Use Factory

public class FactoryPattern {

public static void main(String[] args) {

AnimalFactory animalFactory = new AnimalFactory(); // Get Dog object through factory

Animal dog = animalFactory.getAnimal("dog");



// Call species method of Dog

dog.species();



// Get Cat object through factory

Animal cat = animalFactory.getAnimal("cat");



// Call species of Cat

cat.species();



// Get Bird object through factory

Animal bird = animalFactory.getAnimal("bird");



// Call species of Bird

bird.species();

}

} >> It's a dog.

>> It's a cat.

>> It's a bird.

Conclusion

Factory design pattern contains the logic of how the object is created. It is can also be used to contain all logic for creating new objects. This makes it easier to locate code instead of searching through the entire application. This also makes it easier to add new classes to the factory. If the logic for creating a new object is fairly simple you probably do not need a factory.
['Daniel Liu']
['Backend Development', 'Design Patterns', 'Factory Pattern', 'Java', 'Programming']