Chapter 11: Factory Pattern

大綱

When should you use it?

  • The factory pattern is a creational pattern that provides a way to make objects without exposing creation logic.

    • The factory: creates objects.

    • The products: the objects that are created.

  • When should you use it?

    • Use the factory pattern whenever you want to separate out product creation logic, instead of having consumers create products directly.

Playground example

  • 目標: use a factory to create a “job applicant response” email: The factory can generate email details depending on whether the candidate was accepted, rejected or needs to be interviewed.

  • Objects:

  • Factory

What should you be careful about?

  • Not all polymorphic objects require a factory. If your objects are very simple, you can always put the creation logic directly in the consumer, such as a view controller itself.

  • if your object requires a series of steps to build it, you may be better off using the builder pattern or another pattern instead.

Tutorial project

Key points

  • A factory’s goal is to isolate object creation logic within its own construct.

  • A factory is most useful if you have a group of related products, or if you cannot create an object until more information is supplied (such as completing a network call, or waiting on user input).

  • The factory method adds a layer of abstraction to create objects, which reduces duplicate code.

Last updated