This post gives a brief overview about the Abstract Factory Pattern. The post is part of a series about software design patterns and their UML representations with the help of PlantUML.
The article aims at providing a very short description of the general idea of the pattern in the first part. This also involves a descriptive UML diagram. Then, the second part provides the PlantUML code for the diagram so that these posts can also be used as a source of design patterns in PlantUML syntax.
What is the Abstract Factory Pattern?
According to Wikipedia, the Abstract Factory Pattern solves problems like:
- How can an application be independent of how its objects are created?
- How can a class be independent of how the objects it requires are created?
- How can families of related or dependent objects be created?
Creating objects directly within the class that requires the objects is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects can’t be replaced with mock objects.
The Abstract Factory design pattern describes how to solve such problems:
- Encapsulate object creation in a separate (factory) object. That is, define an interface (AbstractFactory) for creating objects, and implement the interface.
- A class delegates object creation to a factory object instead of creating objects directly.
The following diagram shows the Factory Method Pattern in UML notation. It is based on the corresponding chapter in the book “Head First Design Patterns“:
@startuml skinparam componentStyle uml2 title Abstract Factory Pattern class Client class AbstractFactory <<interface>> class AbstractProductA <<interface>> class ProductA2 class ProductA1 class ConcreteFactory1 class ConcreteFactory2 class AbstractProductB <<interface>> class ProductB1 class ProductB2 AbstractFactory <-- Client Client --> AbstractProductA Client --> AbstractProductB AbstractFactory <|.. ConcreteFactory1 AbstractFactory <|.. ConcreteFactory2 AbstractProductA <|.. ProductA1 AbstractProductA <|.. ProductA2 AbstractProductB <|.. ProductB1 AbstractProductB <|.. ProductB2 ProductA1 <-- ConcreteFactory1 ProductB1 <-- ConcreteFactory1 ProductA2 <-- ConcreteFactory2 ProductB2 <-- ConcreteFactory2 @enduml