Factory Pattern

Tak Yu Chan (Franky)
3 min readOct 25, 2021
Photo by Artur Aldyrkhanov on Unsplash

Intent

Sometime we need to generate an object conditionally, for example as a pizza store, we need to create a lot of different pizzas, the procedure of creating a type of pizza can be complex.

And to follow Single responsibility and Open close principles, we know that we should keep this conditional generate pizza logic in one place instead of letting it pollute other classes.

That’s why we have factory class.

  • SRP: Changed for a single reason
  • OCP: Open for extension as modification can produce unexpected errors
Reference from Head first design patterns, 2nd edition

How to use factory pattern?

There are two “ways” to do it.

  • Simple Factory — Simply encapsulate factory code into another class and use it in the original class directly.
  • Factory method — Implement the original class and implement the factory method to create the instance needed. (for one product)
  • Abstract Factory — Make use of interface for a family of products, use when clients create products that belong together.
Reference from Head First Design Patterns, 2nd Edition

When to use which?

It depends on the problem domain, factory method provides more flexibility but it is more complex than simple factory. We need to assess the trade off by looking at the problem domain and the changing pattern.

Using the pizza store example, in the pizza store we need to fulfil an order by making pizza (vary point), and cutting (assume to be constant) etc.

Simple Factory: If we deadly sure that the software is simple and will never change, then of course we can use simple factory, because it doesn’t provide dependency indirection with interface.

Factory method: Subclass it and implement the factory method to create a single product. (Pizza store)

Reference from Head First Design Patterns, 2nd Edition

Abstract factory: Create a family of related products in one interface, but if later need to expanded/modified, every subtypes need to be changed.

(Use if we already know ahead of time all the concrete classes need to be created, like ingredients)

Reference from Head First Design Patterns, 2nd Edition

--

--