Simple Factory Pattern

Create an object without exposing the instantiation logic to the client.

Concept

In object-oriented programming factory is an object which can create other objects hiding the details from the clients about how the objects are being created. Factory objects helps in dynamically creating objects for clients at run time with varying prototypes. Any subroutine that can create objects is called factory.

A simple factory pattern is considered the simplest form of factory method patterns. So, any applications that follows either the factory method patter or abstract factory method also supports the simple factory patterns design goals.

Analogy

A car owner knows the cars are manufactured in factories and user is least concerned about how the car is built. When the purchase order is created by customer, he receives the car from manufacturer as per-customer interested model and variant

Implementation In Java

Let’s discuss the simple factory pattern design and implementation using java programming language.

Class Diagram


classDiagram
  class SimpleFactory {
    +SimpleFactory()
    +createAnimal(String animal) Animal
  }

  class Animal {
    <<interface>>
    +speak()
    +eat()
  }

  class Dog {
    +Dog()
    +speak()
    +eat()
  }

  class Cat {
    +Cat()
    +speak()
    +eat()
  }

  class Client {
    +process()
  }

  SimpleFactory <-- Client
  SimpleFactory ..> Animal
  Animal <|.. Dog
  Animal <|.. Cat
  

Illustration

The following are the important characteristics of the following implementation.

  • The Dog or Cat object creational process depends upon the client or user input
  • Each animal must implement Animal interface as the factory produces the objects of type Animal
  • When client needs the animal object, client can create simpleFactory object and call createAnimal(String animal) and simpleFactory returns Animal object.
simpleFactory.createAnimal("Cat")
  • The implementation separates the code that likely to vary from its client.

Implementation

Following the code for simple factory in java,

Animal.java

interface Animal {
    void speak();
    default void eat() {
        System.out.println("Yum! Yum!");
    }
}

Cat.java

class Dog implements Animal {

    @Override
    public void speak() {
        System.out.println("Bow! Bow!");
    }
}

Dog.java

class Cat implements Animal {

    @Override
    public void speak() {
        System.out.println("Meow! Meow!");
    }
}

SimpleFactory.java

class SimpleFactory {
    //  default constructor
    public SimpleFactory() { }

    //  createAnimal method implemetation
    public Animal createAnimal(String animal) {
        if (animal == "Cat") return new Cat();
        else if (animal == "Dog") return new Dog();
        else throw new IllegalArgumentException("unknown animal " + animal);
    }
}

Client.java

class Client {
    public void process() {
        //  create factory object
        SimpleFactory simpleFactory = new SimpleFactory();
        //  create cat object
        Animal cat = simpleFactory.createAnimal("Cat");
        cat.speak();
        cat.eat();
        //  create dog object
        Animal dog = simpleFactory.createAnimal("Dog");
        dog.speak();
        dog.eat();
    }
}

Advantages

  • Separates part of the code that’s likely to change from the rest.
  • Only factory is subjected to modify but not client.
  • Object creation is hidden from client.
  • This approach can help avoid lots of if...else blocks on client program. if..else blocks make code clumsy and difficult to understand.

Disadvantages

  • Factory violates Open/Close Principle.
  • Deciding which object to instantiate can become complex over time. In those cases, prefer Factory Method Pattern or Abstract Factory Pattern

When To Use

  • When you want to separate the object creation from its client.
  • Client does not know what objects they have to create at run-time, and they have to rely on helper. (In this case factory)

Known Uses

Factory patterns are heavily used in a good deal of software application frameworks.

Java

The static getInstance() method of the java.text.NumberFormat class is an example of this category.

  • Factory is usually called through Template Method.
  • Factory Methods require subclassing but not instantiation unlike prototype pattern

Learn other design patterns

Subscribe For More Content