The Abstract Factory Design Pattern is a creational design pattern that allows creation of families of related objects.
For example, let’s say that we need to create an application that can generate different document templates. Each template should follow one of the graphics styles: modern, classic, or minimalistic. Also, each template should be available in the following formats: HTML, PDF, and PPT.
When the style is chosen, we want to be able to generate templates in different formats (HTML, PDF, PPT), but each of them should follow the selected graphics style (modern, classic, minimalistic). We want to avoid a mixup situation in which we would select the modern style, and the HTML template would be generated in a desired modern style, but PDF template would be generated in the classic style. It should be impossible to generate HTML in a modern style and PDF in a classic style. Since the Abstract Factory Design Pattern allows us to generate object families, we can use it to get a guarantee that such a mixup will not be possible.
|Modern||Modern Html||Modern PDF||Modern PPT|
|Classic||Classic Html||Classic PDF||Classic PPT|
|Minimalistic||Minimalistic Html||Minimalistic PDF||Minimalistic PPT|
This problem can be modeled in OOP as follows:
In the above example, the
Client holds a reference to the
DocumentTemplateFactory is assigned, the
Client can use
createPPT() to generate document templates. Each created document template will be created in the same style because the style will be dictated by one of the Factory:
MinimalisticStyleTemplateFactory. This approach gives us the flexibility to change the document template style and, at the same time, guarantees that each HTML, PDF, PPT template will be generated in a same desired style.
The Abstract Factory Design Pattern allows the creation of objects that are related in a cohesive manner, ensuring that the objects created by a factory are compatible and adhere to a specific theme or variant. By encapsulating the creation of related objects in a factory, we gain the flexibility of switching the factory that is used to create objects. As a result, different objects are created, and all of them follow the same cohesive theme.
To read more on this and the other patterns, get “GoF Design Patterns Distilled” book from Amazon or Leanpub: