Abstract Factory

AKA: Kit

When finding you need to construct a different set of objects based on the same algorithm, data, or selection of actions, then we want to allow for variability in what we build. Using a Factory Method makes sense for a single object type, but when there are more objects, and they are all related, we need a way to connect the Factory Methods together so they remain coupled correctly.

An Abstract Factory is a base class defining related factory methods. The Abstract Factory can be passed as an object at runtime to allow other methods to control when and what specific classes are instanced.

Abstract Factory

It can be helpful in Builders and Template Methods or other nominalisation of action patterns. A regular find outside of C++ would be a dictionary of functions, lambdas, or prototypes. It depends on the idiom of object creation in the language and project. The keys usually follow a pre-defined naming convention. Abstract Factory can be considered a menu for ordering construction, or objects à la carte if you will.

As we only use the Abstract Factory to relate Factory Methods, it can be stateless and can be safely implemented as a Singleton. The only state for a Abstract Factory would be cross-cutting concerns such as logging or performance statistics.

Each concrete instance of an object-oriented Abstract Factory overrides the factory methods to implement construction.

Making the abstract factory extensible removes the ability to specify how the created components must relate. For example, using a string, enum, or unique-ID allows adding new constructibles at runtime but doesn’t limit what can be added and removes some forms of type safety.

The base Abstract Factory class need not be abstract. It can have concrete methods as defaults and even be a default abstract factory object with other concrete Abstract Factorys overriding as necessary.

“I build furniture of a certain style. Tell me what you want me to build. Chair, table, stool?”