Factory object on:  
[Wikipedia]  
[Google]  
[Amazon]
In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
, a factory is an
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 ai ...
for
creating other objects; formally, it is a
function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-orie ...
or
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
that returns objects of a varying prototype or
class
Class 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 differently ...
from some method call, which is assumed to be "new". More broadly, a subroutine that returns a "new" object may be referred to as a "factory", as in ''factory method'' or ''factory function''. The factory pattern is the basis for a number of related
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 ...
s.
Motivation
In
class-based programming
Class-based programming, or more commonly class-orientation, is a style of object-oriented programming (OOP) in which inheritance occurs via defining '' classes'' of objects, instead of inheritance occurring via the objects alone (compare proto ...
, a factory is an
abstraction
Abstraction in its main sense is a conceptual process wherein general rules and concepts are derived from the usage and classification of specific examples, literal ("real" or " concrete") signifiers, first principles, or other methods.
"An a ...
of a
constructor
Constructor may refer to:
Science and technology
* Constructor (object-oriented programming), object-organizing method
* Constructors (Formula One), person or group who builds the chassis of a car in auto racing, especially Formula One
* Construc ...
of a class, while in
prototype-based programming
Prototype-based programming is a style of object-oriented programming in which behaviour reuse (known as inheritance) is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as ''prototypal ...
a factory is an abstraction of a prototype object. A constructor is concrete in that it creates objects as instances of a single class, and by a specified process (class instantiation), while a factory can create objects by instantiating various classes, or by using other allocation schemes such as an
object pool
The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a " pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the ...
. A prototype object is concrete in that it is used to create objects by being
cloned
Cloning is the process of producing individual organisms with identical or virtually identical DNA, either by natural or artificial means. In nature, some organisms produce clones through asexual reproduction. In the field of biotechnology, ...
, while a factory can create objects by cloning various prototypes, or by other allocation schemes.
A factory may be implemented in various ways. Most often it is implemented as a method, in which case it is called a ''
factory method
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
''. Sometimes it is implemented as a function, in which case it is called a ''factory function''. In some languages, constructors are themselves factories. However, in most languages they are not, and constructors are invoked in a way that is idiomatic to the language, such as by using the keyword
new
, while a factory has no special status and is invoked via an ordinary method call or function call. In these languages, a factory is an abstraction of a constructor, but not strictly a generalization, as constructors are not themselves factories.
Terminology
Terminology differs as to whether the concept of a factory is itself a design pattern – 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 ...
'' there is no "factory pattern", but instead two patterns (
factory method pattern
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
and
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 fa ...
) that use factories. Some sources refer to the concept as the factory pattern,
[Factory Pattern]
OODesign.com
/ref> while others consider the concept itself a programming idiom
In computer programming, a programming idiom or code idiom is a group of code fragments sharing an equivalent semantic role, which recurs frequently across software projects often expressing a special feature of a recurring construct in one or m ...
,[Chapter 4. The Factory Pattern: Baking with OO Goodness]
The Simple Factory defined
reserving the term "factory pattern" or "factory patterns" to more complicated patterns that use factories, most often the factory method pattern; in this context, the concept of a factory itself may be referred to as a simple factory.[ In other contexts, particularly the Python language, "factory" itself is used, as in this article. More broadly, "factory" may be applied not just to an object that returns objects from some method call, but to a '']subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions ma ...
'' that returns objects, as in a ''factory function'' (even if functions are not objects) or ''factory method.'' Because in many languages factories are invoked by calling a method, the general concept of a factory is often confused with the specific factory method pattern
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
design pattern.
Use
OOP provides polymorphism
Polymorphism, polymorphic, polymorph, polymorphous, or polymorphy may refer to:
Computing
* Polymorphism (computer science), the ability in programming to present the same programming interface for differing underlying forms
* Ad hoc polymorphis ...
on object ''use'' by method dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
, formally subtype polymorphism
In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, ...
via single dispatch
In computer science, dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time. It is commonly employed in, and considered a prime characteristic of, object-oriented ...
determined by the type of the object on which the method is called. However, this does not work for constructors, as constructors ''create'' an object of some type, rather than ''use'' an existing object. More concretely, when a constructor is called, there is no object yet on which to dispatch.
Using factories instead of constructors or prototypes allows one to use polymorphism for object creation, not only object use. Specifically, using factories provides encapsulation, and means the code is not tied to specific classes or objects, and thus the class hierarchy or prototypes can be changed or refactored
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structu ...
without needing to change code that uses them – they abstract from the class hierarchy or prototypes.
More technically, in languages where factories generalize constructors, factories can usually be used anywhere constructors can be, meaning that interfaces that accept a constructor can also in general accept a factory – usually one only need something that creates an object, rather than needing to specify a class and instantiation.
For example, in Python, the collections.defaultdict
class has a constructor which creates an object of type defaultdict
whose default values are produced by invoking a factory. The factory is passed as an argument to the constructor, and can itself be a constructor, or any thing that behaves like a constructor – a callable object
A callable object, in computer programming, is any object that can be called like a function.
In different languages
In C++
* pointer to function;
* pointer to member function;
* functor;
* lambda expression.
* std::function is a template ...
that returns an object, i.e., a factory. For example, using the list
constructor for lists:
# collections.defaultdict( efault_factory[, ...)
d = defaultdict(list)
Object creation
Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object, notably if complex allocation or initialization is desired. Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object. The factory object might decide to create the object's class
Class 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 differently ...
(if applicable) dynamically, return it from an object pool
The object pool pattern is a software creational design pattern that uses a set of initialized objects kept ready to use – a " pool" – rather than allocating and destroying them on demand. A client of the pool will request an object from the ...
, do complex configuration on the object, or other things. Similarly, using this definition, a Singleton (mathematics)">singleton
Singleton may refer to:
Sciences, technology Mathematics
* Singleton (mathematics), a set with exactly one element
* Singleton field, used in conformal field theory Computing
* Singleton pattern, a design pattern that allows only one instance of ...
implemented by the singleton pattern is a formal factory – it returns an object, but does not create new objects beyond the single instance.
Examples
The simplest example of a factory is a simple factory function, which just invokes a constructor and returns the result. In Python, a factory function
f
that instantiates a class
A
can be implemented as:
def f():
return A()
A simple factory function implementing the singleton pattern is:
def f():
if f.obj is None:
f.obj = A()
return f.obj
f.obj = None
This will create an object when first called, and always return the same object thereafter.
Syntax
Factories may be invoked in various ways, most often a method call (a ''factory method''), sometimes by being called as a function if the factory is a callable object (a ''factory function''). In some languages constructors and factories have identical syntax, while in others constructors have special syntax. In languages where constructors and factories have identical syntax, like Python, Perl, Ruby, Object Pascal, and F#, constructors can be transparently replaced by factories. In languages where they differ, one must distinguish them in interfaces, and switching between constructors and factories requires changing the calls.
Semantics
In languages where objects are
dynamically allocated, as in Java or Python, factories are semantically equivalent to constructors. However, in languages such as C++ that allow some objects to be statically allocated, factories are different from constructors for statically allocated classes, as the latter can have memory allocation determined at compile time, while allocation of the return values of factories must be determined at run time. If a constructor can be passed as an argument to a function, then invocation of the constructor and allocation of the return value must be done dynamically at run time, and thus have similar or identical semantics to invoking a factory.
Design patterns
Factories are used in various
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 ...
, specifically in
creational pattern
In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems o ...
s such as the
Design pattern object library
A design is a plan or specification for the construction of an object or system or for the implementation of an activity or process or the result of that plan or specification in the form of a prototype, product, or process. The verb ''to design'' ...
. Specific recipes have been developed to implement them in many languages. For example, several "
GoF patterns", like the "
Factory method pattern
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by cr ...
", the "
Builder
Builder may refer to:
* Construction worker, who specializes in building work
* Carpenter, a skilled craftsman who works with wood
* General contractor, that specializes in building work
** Subcontractor
* Builder (detergent), a component of mode ...
" or even the "
Singleton
Singleton may refer to:
Sciences, technology Mathematics
* Singleton (mathematics), a set with exactly one element
* Singleton field, used in conformal field theory Computing
* Singleton pattern, a design pattern that allows only one instance of ...
" are implementations of this concept. The "
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 fa ...
" instead is a method to build collections of factories.
In some design patterns, a factory object has a
method
Method ( grc, μέθοδος, methodos) literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In recent centuries it more often means a prescribed process for completing a task. It may refer to:
*Scien ...
for every kind of object it is capable of creating. These methods optionally accept
parameter
A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
s defining how the object is created, and then return the created object.
Applications
Factory objects are common in
toolkit A toolkit is an assembly of tools; set of basic building units for user interfaces.
The word toolkit may refer to:
* Abstract Window Toolkit
* Accessibility Toolkit
* Adventure Game Toolkit
* B-Toolkit
* Battlefield Mod Development Toolkit
* Chemi ...
s and
frameworks
A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of.
Framework may refer to:
Computing
* Application framework, used to implement the structure of an application for an op ...
where library code needs to create objects of types which may be subclassed by applications using the framework. They are also used in
test-driven development
Test-driven development (TDD) is a software development process relying on software requirements being converted to test cases before software is fully developed, and tracking all software development by repeatedly testing the software against a ...
to allow classes to be put under test.
Factories determine the actual ''concrete'' type of
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 ai ...
to be created, and it is here that the object is actually created. As the factory only returns an abstract interface to the object, the client code does not know – and is not burdened by – the actual concrete type of the object which was just created. However, the type of a concrete object is known by the abstract factory. 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
Class 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 differently ...
declarations relating to the concrete type. 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
In computing, an abstraction layer or abstraction level is a way of hiding the working details of a subsystem. Examples of software models that use layers of abstraction include the OSI model for network protocols, OpenGL, and other graphics librar ...
.
* Adding new concrete types is done by modifying the client code to use a different factory, a modification which is typically one line in one file. 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.
Applicability
Factories can be used when:
# The creation of an object makes reuse impossible without significant duplication of code.
# The creation of an object requires access to information or resources that should not be contained within the composing class.
# The lifetime management of the generated objects must be centralized to ensure a consistent behavior within the application.
Factories, specifically factory methods, are common in
toolkit A toolkit is an assembly of tools; set of basic building units for user interfaces.
The word toolkit may refer to:
* Abstract Window Toolkit
* Accessibility Toolkit
* Adventure Game Toolkit
* B-Toolkit
* Battlefield Mod Development Toolkit
* Chemi ...
s and
frameworks
A framework is a generic term commonly referring to an essential supporting structure which other things are built on top of.
Framework may refer to:
Computing
* Application framework, used to implement the structure of an application for an op ...
, where library code needs to create objects of types that may be subclassed by applications using the framework.
Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.
Factory methods are used in
test-driven development
Test-driven development (TDD) is a software development process relying on software requirements being converted to test cases before software is fully developed, and tracking all software development by repeatedly testing the software against a ...
to allow classes to be put under test. If such a class
Foo
creates another object
Dangerous
that can't be put under automated
unit test
In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures&m ...
s (perhaps it communicates with a production database that isn't always available), then the creation of
Dangerous
objects is placed in the
virtual
Virtual may refer to:
* Virtual (horse), a thoroughbred racehorse
* Virtual channel, a channel designation which differs from that of the actual radio channel (or range of frequencies) on which the signal travels
* Virtual function, a programming ...
factory method
createDangerous
in class
Foo
. For testing,
TestFoo
(a subclass of
Foo
) is then created, with the virtual factory method
createDangerous
overridden to create and return
FakeDangerous
, a
fake object
In object-oriented programming, mock objects are simulated objects that mimic the behaviour of real objects in controlled ways, most often as part of a software testing initiative. A programmer typically creates a mock object to test the behaviou ...
. Unit tests then use
TestFoo
to test the functionality of
Foo
without incurring the side effect of using a real
Dangerous
object.
Benefits and variants
Besides use in design patterns, factories, especially factory methods, have various benefits and variations.
Descriptive names
A factory method has a distinct name. In many object-oriented languages, constructors must have the same name as the class they are in, which can lead to ambiguity if there is more than one way to create an object (see
overloading). Factory methods have no such constraint and can have descriptive names; these are sometimes known as alternative constructors. As an example, when
complex number
In mathematics, a complex number is an element of a number system that extends the real numbers with a specific element denoted , called the imaginary unit and satisfying the equation i^= -1; every complex number can be expressed in the for ...
s are created from two real numbers the real numbers can be interpreted as Cartesian or polar coordinates, but using factory methods, the meaning is clear, as illustrated by the following example in C#.
public class Complex
Complex product = Complex.FromPolar(1, Math.PI);
When factory methods are used for disambiguation like this, the raw constructors are often made private to force clients to use the factory methods.
Encapsulation
Factory methods encapsulate the creation of objects.
This can be useful if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.
Consider as an example a program that reads
image file
An Image file format is a file format for a digital image. There are many formats that can be used, such as JPEG, PNG, and GIF. Most formats up until 2022 were for storing 2D images, not 3D ones. The data stored in an image file format may be ...
s. The program supports different image formats, represented by a reader class for each format.
Each time the program reads an image, it needs to create a reader of the appropriate type based on some information in the file. This logic can be encapsulated in a factory method. This approach has also been referred to as the Simple Factory.
Java
public class ImageReaderFactory
PHP
class Factory
interface FormatInterface
class FormatString implements FormatInterface
class FormatNumber implements FormatInterface
try catch (Exception $e)
try catch (Exception $e)
Limitations
There are three limitations associated with the use of the factory method. The first relates to
refactoring
In computer programming and software design, code refactoring is the process of restructuring existing computer code—changing the '' factoring''—without changing its external behavior. Refactoring is intended to improve the design, structu ...
existing code; the other two relate to extending a class.
* The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were a standard class, it might have numerous clients with code like:
Complex c = new Complex(-1, 0);
:Once we realize that two different factories are needed, we change the class (to the code shown
earlier). But since the constructor is now private, the existing client code no longer compiles.
* The second limitation is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private.
* The third limitation is that, if the class were to be extended (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if class
StrangeComplex
extends
Complex
, then unless
StrangeComplex
provides its own version of all factory methods, the call
StrangeComplex.FromPolar(1, Math.Pi); will yield an instance of
Complex
(the superclass) rather than the expected instance of the subclass. The
reflection features of some languages can avoid this issue.
All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also
Virtual class
In object-oriented programming, a virtual base class is a nested inner class whose functions and member variables can be overridden and redefined by subclasses of an outer class. Virtual classes are analogous to virtual functions.
The run time ty ...
).
Notes
References
*
{{refend
Object-oriented programming
Articles with example C Sharp code
Articles with example Java code
Articles with example PHP code
zh:工厂方法#工厂