The abstract factory pattern in
software engineering
Software engineering is a branch of both computer science and engineering focused on designing, developing, testing, and maintaining Application software, software applications. It involves applying engineering design process, engineering principl ...
is a design pattern that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual
factories
A factory, manufacturing plant or production plant is an industrial facility, often a complex consisting of several buildings filled with machinery, where workers manufacture items or operate machines which process each item into another. Th ...
that have a common theme without specifying their concrete classes.
According to this pattern, a client software component creates a concrete implementation of the abstract factory and then uses the generic
interface of the factory to create the concrete
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
s that are part of the family. The
client does not know which concrete objects it receives from each of these internal factories, as 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 l ...
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.
Use of this pattern enables interchangeable 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" ...
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 23 patterns described in the 1994 ''
Design Patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a fore ...
'' book. It may be used to solve problems such as:
* How can an application be independent of how its objects are created?
* How can a class be independent of how the objects that 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. Doing so commits the class to particular objects and makes it impossible to change the instantiation later without changing the class. It prevents the class from being reusable if other objects are required, and it makes the class difficult to test because real objects cannot be replaced with mock objects.
A factory is the location of a concrete class in the code at which
objects are constructed. Implementation of the pattern intends to insulate the creation of objects from their usage and to create families of related objects without depending on their concrete classes.
This allows for new
derived types to be introduced with no change to the code that uses the
base class.
The pattern describes how to solve such problems:
*
Encapsulate object creation in a separate (factory) object by defining and implementing an interface for creating objects.
* Delegate object creation to a factory object instead of creating objects directly.
This makes a class independent of how its objects are created. A class may be configured with a factory object, which it uses to create objects, and the factory object can be exchanged at runtime.
Definition
''Design Patterns'' describes the abstract factory pattern as "an interface for creating families of related or dependent objects without specifying their concrete classes."
Usage
The factory determines the concrete type of object to be created, and it is here that the object is actually created. However, the factory only returns a reference (in Java, for instance, by the new
operator) or a
pointer of an abstract type to the created concrete object.
This insulates client code from
object creation
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
by having clients request that a
factory object create an object of the desired
abstract type
In programming languages, an abstract type (also known as existential types) is a type in a nominative type system that cannot be instantiated directly; by contrast, a concrete type be instantiated directly. Instantiation of an abstract ty ...
and return an abstract pointer to the object.
An example is 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 such as
FancyDocumentCreator
or
ModernDocumentCreator
, each with a different implementation of
createLetter()
and
createResume()
that would create corresponding objects such as
FancyLetter
or
ModernResume
. Each of these products is derived from a simple
abstract class
In object-oriented programming, a class defines the shared aspects of objects created from the class. The capabilities of a class differ between programming languages, but generally the shared aspects consist of state ( variables) and behavior ( ...
such as
Letter
or
Resume
of which the client is aware. The client code would acquire 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 was created by the concrete factory.
As the factory only returns a reference or a pointer to an abstract type, the client code that requested the object from the factory is not aware of—and is not burdened by—the actual concrete type of the object that was created. However, the abstract factory knows the type of a concrete object (and hence a concrete factory). For instance, the factory may read the object's type from a configuration file. The client has no need to specify the type, as the type has already been specified in the configuration file. In particular, this means:
* The client code has no knowledge 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.
* ...
, not needing to include any
header file
An include directive instructs a text file processor to replace the directive text with the content of a specified file.
The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
s or
class
Class, Classes, or The Class may refer to:
Common uses not otherwise categorized
* Class (biology), a taxonomic rank
* Class (knowledge representation), a collection of individuals or objects
* Class (philosophy), an analytical concept used d ...
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 interfaces.
* Adding new concrete types is performed 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. Doing so would require changing every location in the code where a new object is created as well as ensuring that all such code locations have knowledge of the new concrete type, for example, by including a concrete class header file. If all factory objects are stored globally in a
singleton object, and all client code passes 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 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 re ...
,
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 sequence diagram
In software engineering, a sequence diagram
shows process interactions arranged in time sequence. This diagram depicts the processes and objects involved and the sequence of messages exchanged as needed to carry out the functionality. Sequence ...
shows the runtime 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.
Variants
The original structure of the abstract factory pattern, as defined in 1994 in ''
Design Patterns
''Design Patterns: Elements of Reusable Object-Oriented Software'' (1994) is a software engineering book describing software design patterns. The book was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a fore ...
'', is based on abstract classes for the abstract factory and the abstract products to be created. The concrete factories and products are classes that specialize the abstract classes using inheritance.
A more recent structure of the pattern is based on interfaces that define the abstract factory and the abstract products to be created. This design uses native support for interfaces or protocols in mainstream programming languages to avoid inheritance. In this case, the concrete factories and products are classes that realize the interface by implementing it.
Example
This
C++23
C++23, formally ISO/IEC 14882:2024, is the current open standard for the C++ programming language that follows C++20. The final draft of this version is N4950.
In February 2020, at the final meeting for C++20 in Prague, an overall plan for C++ ...
implementation is based on the pre-C++98 implementation in the book.
import std;
enum class Direction ;
class MapSite ;
class Room: public MapSite ;
class Wall: public MapSite ;
class Door: public MapSite ;
class Maze ;
class MazeFactory ;
// If createMaze is passed an object as a parameter to use to create rooms, walls, and doors, then you can change the classes of rooms, walls, and doors by passing a different parameter. This is an example of the Abstract Factory (99) pattern.
class MazeGame ;
int main()
The program output is:
Maze::addRoom 0x1317ed0
Maze::addRoom 0x1317ef0
Room::setSide 0 0x1318340
Room::setSide 2 0x1317f10
Room::setSide 1 0x1318360
Room::setSide 3 0x1318380
Room::setSide 0 0x13183a0
Room::setSide 2 0x13183c0
Room::setSide 1 0x13183e0
Room::setSide 3 0x1317f10
See also
*
Concrete class
In object-oriented programming, a class defines the shared aspects of objects created from the class. The capabilities of a class differ between programming languages, but generally the shared aspects consist of state ( variables) and behavior ( ...
*
Factory method pattern
In object-oriented programming, the factory method pattern is a software design pattern, design pattern that uses factory methods to deal with the problem of object creation, creating objects without having to specify their exact class (computer pr ...
*
Object creation
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an a ...
*
Software design pattern
In software engineering, a software design pattern or design pattern is a general, reusable solution to a commonly occurring problem in many contexts in software design. A design pattern is not a rigid structure to be transplanted directly into s ...
References
External links
*
Abstract FactoryAbstract Factory implementation example
{{Design patterns
Software design patterns
Articles with example C++ code