Factory Method

We've already looked at the Abstract Factory and Builder patterns. The Abstract Factory pattern builds a family of related classes and the builder creates complicated objects using different strategies. The Factory Method pattern allows a class to request a new instance of an interface without the class making decisions about which implementation of the interface to use. The factory may use some strategy to select which implementation to return. This is shown in the following diagram:

Factory Method

Sometimes, this strategy is simply to take a string parameter or to examine some global setting to act as a switch.

Implementation

In our example world ...

Get Mastering JavaScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.