Abstract Factory
Problem
Suppose there are 3 types of products (families) and each product has 3 variants, then there are 9 products in total.
With regular factory method, we have one factory for each product (in this case, family), but what if we want to add a new variant without changing existing code?
Solution
-
Declare an interface for each product family
Variants of each product family need to implement these interfaces.
-
Declare AbstractFactory interface
It has some methods that return abstract product types (family), such as
- createChair -> Chair
- createTable -> Table
- createSofa -> Sofa
-
For each variant of a product family, create a separate factory class based on AbstractFactory interface. Each factory is responsible for creating the products of a single variant.
-
Client (Application) doesn't need to know which type of factory is used, a concrete factory object could be passed to the application (created beforehand based on some parameters).
Sample Code
Products
Factory
Application (Client)
Demo
Limitation
Reference
How is this guide?