layout: pattern
title: Factory
folder: factory
permalink: /patterns/factory/
categories: Creational
tags:

  • Gang of Four

Also known as

  • Simple Factory
  • Static Factory Method

Intent

Providing a static method encapsulated in a class called factory, in order to hide the
implementation logic and makes client code focus on usage rather then initialization new objects.

Explanation

Real world example

Lets say we have a web application connected to SQLServer, but now we want to switch to Oracle. To do so without modifying existing source code, we need to implements Simple Factory pattern, in which a static method can be invoked to create connection to a given database.

Wikipedia says

Factory is an object for creating other objects – formally a factory is a function or method that returns objects of a varying prototype or class.

Programmatic Example

We have an interface Car and two implementations Ford and Ferrari.

  1. public interface Car {
  2. String getDescription();
  3. }
  4. public class Ford implements Car {
  5. static final String DESCRIPTION = "This is Ford.";
  6. @Override
  7. public String getDescription() {
  8. return DESCRIPTION;
  9. }
  10. }
  11. public class Ferrari implements Car {
  12. static final String DESCRIPTION = "This is Ferrari.";
  13. @Override
  14. public String getDescription() {
  15. return DESCRIPTION;
  16. }
  17. }

Enumeration above represents types of cars that we support (Ford and Ferrari).

  1. public enum CarType {
  2. FORD(Ford::new),
  3. FERRARI(Ferrari::new);
  4. private final Supplier<Car> constructor;
  5. CarType(Supplier<Car> constructor) {
  6. this.constructor = constructor;
  7. }
  8. public Supplier<Car> getConstructor() {
  9. return this.constructor;
  10. }
  11. }

Then we have the static method getCar to create car objects encapsulated in the factory class
CarsFactory.

  1. public class CarsFactory {
  2. public static Car getCar(CarType type) {
  3. return type.getConstructor().get();
  4. }
  5. }

Now on the client code we can create different types of cars using the factory class.

  1. var car1 = CarsFactory.getCar(CarType.FORD);
  2. var car2 = CarsFactory.getCar(CarType.FERRARI);
  3. LOGGER.info(car1.getDescription());
  4. LOGGER.info(car2.getDescription());

Program output:

  1. This is Ford.
  2. This Ferrari.

Class Diagram

👨‍🏭 simple factory - 图1 👨‍🏭 simple factory - 图2

Applicability

Use the Simple Factory pattern when you only care about the creation of an object, not how to create
and manage it.

Pros

  • Allows keeping all objects creation in one place and avoid of spreading ‘new’ keyword across codebase.
  • Allows to write loosely coupled code. Some of its main advantages include better testability, easy-to-understand code, swappable components, scalability and isolated features.

Cons

  • The code becomes more complicated than it should be.