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 pr ...
, 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-oriente ...
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 differentl ...
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 code ...
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 prototy ...
, 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 abstr ...
of a
constructor 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 po ...
. 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, c ...
, 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 foreword ...
'' 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 mo ...
,[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 may ...
'' 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 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, structur ...
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_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_(computer_science)">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_differentl_...
_(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_po_...
,_do_complex_configuration_on_the_object,_or_other_things._Similarly,_using_this_definition,_a_Singleton_(mathematics).html" "title="class_(computer_science).html" "title="_....html" ;"title="efault_factory[, ...">efault_factory[, ...)
d = defaultdict(list)
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 (computer science)">class