Abstract Factory
04 Mar 2022Intent
Provide an interface for creating families of related or dependent objects without specifying their concrete class.
Also known as
Kit.
Applicability
Use abstract factory pattern when:
- A system should be independent of how it's products are created, composed and represented.
- A system should be configured with one of multiple families of product.
- A family of related product objects is designed to be used together, and you need to enforce the constraint.
- You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Structure
Participants
- Abstract Factory: declares an interface for operations that create abstract product objects.
- Concerete Factory: implements the operations to create concrete product objects.
- Abstract Product: declares an interface for a type of product object.
- Concrete Product: defines product objects to be created by corresponding concrete factory. It implements the AbstractProduct interface
- Client: uses only interfaces declared by AbstractFactory and AbstractProduct classes.
Collaborations
- Normally a single instance of ConcreteFactory class is created ar runtime. This concrete factory creates products objects having a particular implementation.
- AbstractFactory defers creation of product objects to its ConcreteFactory subclass.
Consequences
Abstract Factory has the below benefits/liabilities:
- It isolates concrete classes.
- It makes exchanging product families easy.
- It promotes consistency among products.
- Supporting new kind of products is difficult.
Sample Code
Related Patterns
- Abstract Factory classes are often implemented with Factory Method, but can also be implemented using Prototype
- A concrete factory is often a Singleton