Abstract factory pattern


The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client does not know which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.
An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products and createResume). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter and createResume that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme. The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory.
A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes. This allows for new derived types to be introduced with no change to the code that uses the base class.
Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems that are more difficult to debug and maintain.

Overview

The Abstract Factory
design pattern is one of the twenty-three well-known
GoF design patterns
that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
The Abstract Factory design pattern solves problems like:
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 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 cannot be replaced with mock objects.
The Abstract Factory design pattern describes how to solve such problems:
This makes a class independent of how its objects are created.
A class can be configured with a factory object, which it uses to create objects, and even more, the factory object can be exchanged at run-time.

Definition

The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.".

Usage

The factory determines the actual concrete type of object to be created, and it is here that the object is actually created. However, the factory only returns an abstract pointer to the created concrete object.
This insulates client code from object creation by having clients ask a factory object to create an object of the desired abstract type and to return an abstract pointer to the object.
As the factory only returns an abstract pointer, the client code does not know — and is not burdened by — the actual concrete type of the object that was just created. However, the type of a concrete object is known by the abstract factory; for instance, the factory may read it from a configuration file. The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:

UML diagram

In the above UML class diagram,
the Client class that requires ProductA and ProductB objects does not instantiate the ProductA1 and ProductB1 classes directly.
Instead, the Client refers to the AbstractFactory interface for creating objects,
which makes the Client independent of how the objects are created.
The Factory1 class implements the AbstractFactory interface by instantiating the ProductA1 and ProductB1 classes.
The UML sequence diagram shows the run-time interactions:
The Client object calls createProductA on the Factory1 object, which creates and returns a ProductA1 object.
Thereafter,
the Client calls createProductB on Factory1, which creates and returns a ProductB1 object.

Lepus3 chart

Java example

The full implementation of the Abstract Factory pattern is available at https://java-design-patterns.com/patterns/abstract-factory/. Here is the shortened version.
King.java

public interface King

Army.java

public interface Army

ElfKing.java

public class ElfKing implements King

ElfArmy.java

public class ElfArmy implements Army

KingdomFactory.java

public interface KingdomFactory

ElfKingdomFactory.java

public class ElfKingdomFactory implements KingdomFactory

App.java

var factory = new ElfKingdomFactory;
var king = factory.createKing;
var army = factory.createArmy;
king.getDescription;
army.getDescription;

Program output

This is the Elven king!
This is the Elven Army!

Python">Python (programming language)">Python example


from abc import ABC, abstractmethod
from sys import platform
class Button:
@abstractmethod
def paint:
pass
class LinuxButton:
def paint:
return 'Render a button in a Linux style'
class WindowsButton:
def paint:
return 'Render a button in a Windows style'
class MacOSButton:
def paint:
return 'Render a button in a MacOS style'
class GUIFactory:
@abstractmethod
def create_button:
pass
class LinuxFactory:
def create_button:
return LinuxButton
class WindowsFactory:
def create_button:
return WindowsButton
class MacOSFactory:
def create_button:
return MacOSButton
if platform 'linux':
factory = LinuxFactory
elif platform 'darwin':
factory = MacOSFactory
elif platform 'win32':
factory = WindowsFactory
else:
raise NotImplementedError
button = factory.create_button
result = button.paint
print

Alternative implementation using the classes themselves as factories:

from abc import ABC, abstractmethod
from sys import platform
class Button:
@abstractmethod
def paint:
pass
class LinuxButton:
def paint:
return 'Render a button in a Linux style'
class WindowsButton:
def paint:
return 'Render a button in a Windows style'
class MacOSButton:
def paint:
return 'Render a button in a MacOS style'
if platform "linux":
factory = LinuxButton
elif platform "darwin":
factory = MacOSButton
elif platform "win32":
factory = WindowsButton
else:
raise NotImplementedError
button = factory
result = button.paint
print