DEV Community

jzfrank
jzfrank

Posted on

HFDP(4) - Factory Pattern

In this post we will discuss the factory pattern.

So, there are actually three kinds of patterns that could be classified into "factory pattern":

  • Simple Factory Pattern
  • Factory Method Pattern
  • Abstract Factory Pattern

All of them try to decouple the creator from its products. There are things that classes have in common, for example, in a pizzaStore, when a customer orderPizza, the store needs to createPizza and prepare, cut, box, deliver pizza. We can see that prepare, cut, box, deliver pizza are more or less the same, we may just reuse the code. However, the actually pizza we want to create might be different. The New York pizza is very different from Chicago pizza. (or without the purpose of offending, Hawaii pizza and Italian pizza). We may choose to code this differently:

  • Pass a factory that makes pizza to the PizzaStore, the factory should have a method that createPizza (usually parametrized). This will be Simple Factory Pattern.

  • Make PizzaStore an abstract class with abstract method createPizza. Then, each concrete pizzaStore like NYPizzaStore should inherit PizzaStore and implement createPizza differently. This will be Factory Method Pattern.

  • If we group similar objects together, and uses composition more than inheritance, it's Abstract Factory Pattern. But it is very similar to Factory Method Pattern. In PizzaStore example, we will have many interfaces PizzaStore, Pizza, PizzaIngredientFactory, Clam (and other ingredients like Cheese, Pepperoni)

Formal Definition

Simple Factory Pattern

The Simple Factory isn’t actually a Design Pattern; it’s more of a programming idiom.

Simple Factory Pattern

Factory Method Pattern

The Factory Method Pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory Method Pattern

Abstract Factory Pattern

The Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

(I feel like it's creating a bunch of interfaces that make objects communicate through interfaces, while they have a flavor of factory method pattern and creator-product relation.)

Abstract Factory Pattern

Design Principle

The Dependency Inversion Principle

Depend on abstractions. Do not depend on concrete classes.

This is a bit similar to Program to an interface, not an implementation. However, this statement suggests our high level components should NOT depend on low level components, they should both depend on abstractions

Dependency Inversion Principle

That's it for today. This is a really long chapter...

Top comments (0)