Factory Pattern

The factory pattern simply generates an instance for client without exposing its instantiation logic to the client.

class_diagram_of_factory_pattern_in_java1-8964987

In object-oriented programming (OOP), a factory is an object used to create other objects. In other words, a factory is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be “new“.

Factory pattern simply generates an instance for client without exposing its instantiation logic to the client.

As the name suggests, a factory is a place where different products are created, similar in features yet divided into categories. In Java, a factory pattern is used to create instances of different classes of the same type.

We use the factory pattern because if the object creation logic is spread throughout the whole application, and if we need to change the object creation process, you must go to every place to make the necessary changes. Factory patterns help put the object creation logic in a central place so changes can be made easily.

1. When to use Factory Pattern?

The factory pattern introduces loose coupling between classes, which is the most important principle to consider and apply while designing application architecture. Loose coupling can be introduced in application architecture by programming against abstract entities rather than concrete implementations. This not only makes our architecture more flexible but also less fragile.

A picture is worth a thousand words. Let’s see what a factory implementation will look like.

class_diagram_of_factory_pattern_in_java1-8964987

The above class diagram depicts a typical scenario using an example of a car factory that can build three types of cars: small, sedan, and luxury. Building a car requires many steps, from allocating accessories to final makeup. These steps can be written in programming as methods and should be called while creating a specific car-type instance.

2. Factory Pattern Implementation

So far, we have designed the classes that need to be designed for making a CarFactory. Let’s code them now.

2.1. Car Types

The CarType enum will hold the types of cars and will provide car types to all other classes.

public enum CarType {

    SMALL, SEDAN, LUXURY
}

2.2. Car Implementations

The Car is the parent class of all car instances, and it will also contain the common logic applicable to car making of all types.

public abstract class Car {
 
  public Car(CarType model) {
    this.model = model;
    arrangeParts();
  }
 
  private void arrangeParts() {
    // Do one time processing here
  }
 
  // Do subclass level processing in this method
  protected abstract void construct();
 
  private CarType model = null;
 
  public CarType getModel() {
    return model;
  }
 
  public void setModel(CarType model) {
    this.model = model;
  }
}

LuxuryCar is the concrete implementation of car type LUXURY.

public class LuxuryCar extends Car {
 
  LuxuryCar() {
    super(CarType.LUXURY);
    construct();
  }
 
  @Override
  protected void construct() {
    System.out.println("Building luxury car");
    // add accessories
  }
}

SmallCar is the concrete implementation of car type SMALL.

public class SmallCar extends Car {
 
  SmallCar() {
    super(CarType.SMALL);
    construct();
  }
 
  @Override
  protected void construct() {
    System.out.println("Building small car");
    // add accessories
  }
}

SedanCar is the concrete implementation of car type SEDAN.

public class SedanCar extends Car {
 
  SedanCar() {
    super(CarType.SEDAN);
    construct();
  }
 
  @Override
  protected void construct() {
    System.out.println("Building sedan car");
    // add accessories
  }
}

2.3. Factory to Create Objects

CarFactory.java is our main class implemented using factory pattern. It instantiates a car instance only after determining its type.

public class CarFactory {

  public static Car buildCar(CarType model) {

    Car car = null;

    switch (model) {
    case SMALL:
      car = new SmallCar();
      break;
 
    case SEDAN:
      car = new SedanCar();
      break;
 
    case LUXURY:
      car = new LuxuryCar();
      break;
 
    default:
      // throw some exception
      break;
    }
    return car;
  }
}

3. Demo

In TestFactoryPattern, we will test our factory code. Let us run this class.

public class TestFactoryPattern {

  public static void main(String[] args) {

    System.out.println(CarFactory.buildCar(CarType.SMALL));
    System.out.println(CarFactory.buildCar(CarType.SEDAN));
    System.out.println(CarFactory.buildCar(CarType.LUXURY));
  }
}

Program Output.

Building small car
designPatterns.creational.factory.SmallCar@7c230be4
Building sedan car
designPatterns.creational.factory.SedanCar@60e1e567
Building luxury car
designPatterns.creational.factory.LuxuryCar@e9bfee2

As you can see, the factory can return any type of car instance it is requested for. It will help us in making any kind of changes in the making process without even touching the composing classes i.e. classes using CarFactory.

4. Benefits of Factory Pattern

By now, you should be able to count the main advantages of using the factory pattern. Let’s note down:

  • The creation of an object precludes its reuse without significant duplication of code.
  • The creation of an object requires access to information or resources that should not be contained within the composing class.
  • The lifetime management of the generated objects must be centralized to ensure consistent behavior within the application.

5. Summary

Factory pattern is most suitable where some complex object creation steps are involved. A factory pattern should be used to ensure these steps are centralized and not exposed to composing classes. We can see many real-life examples of factory patterns in JDK itself, e.g.

I hope I have included enough information in this Java factory pattern example to make this post informative.

If you still have questions about the abstract factory design pattern in Java, please leave a comment. I’ll be happy to discuss it with you.

Happy Learning !!

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
48 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.