The abstract factory pattern provides a way to encapsulate a group of individual
factories
A factory, manufacturing plant or a production plant is an industrial facility, often a complex consisting of several buildings filled with machinery
A machine is a physical system using power to apply forces and control movement to p ...
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
Interface or interfacing may refer to:
Academic journals
* ''Interface'' (journal), by the Electrochemical Society
* '' Interface, Journal of Applied Linguistics'', now merged with ''ITL International Journal of Applied Linguistics''
* '' Int ...
of the factory to create the concrete
objects that are part of the theme. The
client
Client(s) or The Client may refer to:
* Client (business)
* Client (computing), hardware or software that accesses a remote service on another computer
* Customer or client, a recipient of goods or services in return for monetary or other valuabl ...
does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.
This
pattern
A pattern is a regularity in the world, in human-made design, or in abstract ideas. As such, the elements of a pattern repeat in a predictable manner. A geometric pattern is a kind of pattern formed of geometric shapes and typically repeated li ...
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 (e.g.,
createLetter()
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
Client(s) or The Client may refer to:
* Client (business)
* Client (computing), hardware or software that accesses a remote service on another computer
* Customer or client, a recipient of goods or services in return for monetary or other valuabl ...
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 (they would all be fancy or modern objects). 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 pattern
A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" b ...
s, 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:
* 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 cannot 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.
This makes a class independent of how its objects are created (which concrete classes are instantiated).
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 (in Java, for instance, by the new
operator
Operator may refer to:
Mathematics
* A symbol indicating a mathematical operation
* Logical operator or logical connective in mathematical logic
* Operator (mathematics), mapping that acts on elements of a space to produce elements of another ...
). However, the factory only returns an ''abstract''
pointer
Pointer may refer to:
Places
* Pointer, Kentucky
* Pointers, New Jersey
* Pointers Airport, Wasco County, Oregon, United States
* The Pointers, a pair of rocks off Antarctica
People with the name
* Pointer (surname), a surname (including a list ...
to the created
concrete object.
This insulates client code from
object creation
In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementa ...
by having clients ask a
factory object to create an object of the desired
abstract type
In programming languages, an abstract type is a type in a nominative type system that cannot be instantiated directly; a type that is not abstract – which ''can'' be instantiated – is called a ''concrete type''. Every instance of an abstra ...
and to return an abstract pointer to the object.
As the factory only returns an abstract pointer, the client code (that requested the object from the factory) 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 (and hence a concrete factory) 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:
* The client code has no knowledge whatsoever of the concrete
type
Type may refer to:
Science and technology Computing
* Typing, producing text via a keyboard, typewriter, etc.
* Data type, collection of values used for computations.
* File type
* TYPE (DOS command), a command to display contents of a file.
* Ty ...
, not needing to include any
header file
Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
s or
class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their
abstract interface.
* Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. The different factory then creates objects of a ''different'' concrete type, but still returns a pointer of the ''same'' abstract type as before — thus insulating the client code from change. This is significantly easier than modifying the client code to instantiate a new type, which would require changing ''every'' location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a
singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.
Structure
UML diagram
In the above
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally ...
class diagram
In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the r ...
,
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 (which concrete classes are instantiated).
The
Factory1
class implements the
AbstractFactory
interface by instantiating the
ProductA1
and
ProductB1
classes.
The
UML
The Unified Modeling Language (UML) is a general-purpose, developmental modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
The creation of UML was originally ...
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
Python example
from abc import ABC, abstractmethod
from sys import platform
class Button(ABC):
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in a Linux style"
class WindowsButton(Button):
def paint(self):
return "Render a button in a Windows style"
class MacOSButton(Button):
def paint(self):
return "Render a button in a MacOS style"
class GUIFactory(ABC):
@abstractmethod
def create_button(self):
pass
class LinuxFactory(GUIFactory):
def create_button(self):
return LinuxButton()
class WindowsFactory(GUIFactory):
def create_button(self):
return WindowsButton()
class MacOSFactory(GUIFactory):
def create_button(self):
return MacOSButton()
if platform "linux":
factory = LinuxFactory()
elif platform "darwin":
factory = MacOSFactory()
elif platform "win32":
factory = WindowsFactory()
else:
raise NotImplementedError(f"Not implemented for your platform: ")
button = factory.create_button()
result = button.paint()
print(result)
Alternative implementation using the classes themselves as factories:
from abc import ABC, abstractmethod
from sys import platform
class Button(ABC):
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in a Linux style"
class WindowsButton(Button):
def paint(self):
return "Render a button in a Windows style"
class MacOSButton(Button):
def paint(self):
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(f"Not implemented for your platform: ")
button = factory()
result = button.paint()
print(result)
See also
*
Concrete class
*
Factory method pattern
*
Object creation
In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementa ...
*
Software design pattern
In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine c ...
References
External links
Abstract Factoryimplementation in Java
*
Abstract FactoryUML diagram + formal specification in LePUS3 and Class-Z (a Design Description Language)
Abstract Factory implementation example
{{Design Patterns Patterns
Software design patterns
Articles with example C++ code
Articles with example Java code
Articles with example Python (programming language) code