The Factory Pattern
The Factory pattern is another creational pattern concerned with the notion of creating objects. Where it differs from the other patterns in its category is that it doesn’t explicitly require the use of a constructor. Instead, a Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to be created (Figure 9-9).

Figure 9-9. Factory pattern
Imagine that we have a UI factory where we are asked to create a
type of UI component. Rather than creating this component directly using
the new operator or via another
creational constructor, we ask a Factory object for a new component
instead. We inform the Factory what
type of object is required (e.g., “Button”, “Panel”) and it instantiates
this, returning it to us for use.
This is particularly useful if the object creation process is relatively complex—e.g., if it strongly depends on dynamic factors or application configuration.
Examples of this pattern can be found in UI libraries such as ExtJS, where the methods for creating objects or components may be further subclassed.
The following is an example that builds upon our previous snippets
using the Constructor pattern logic to define cars. It demonstrates how a
vehicle factory may be implemented using the Factory
pattern:
// Types.js - Constructors used behind the scenes// A constructor for defining new carsfunction ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access