In
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of '' objects''. Objects can contain data (called fields, attributes or properties) and have actions they can perform (called procedures or methods and impl ...
, the factory method pattern is a
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" ...
that uses factory methods to deal with the problem of
creating objects without having to specify their exact
classes. Rather than by calling a
constructor, this is accomplished by invoking a factory method to create an object. Factory methods can be specified in an
interface and implemented by subclasses or implemented in a base class and optionally
overridden by subclasses. It is one of the 23 classic design patterns described in the book ''
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 ...
'' (often referred to as the "Gang of Four" or simply "GoF") and is subcategorized as a
creational pattern
In software engineering, creational design patterns are design patterns that deal with object creation
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not ex ...
.
Overview
The factory method design pattern solves problems such as:
* How can an object's
subclasses redefine its subsequent and distinct implementation? The pattern involves creation of a factory method within the
superclass that defers the object's creation to a subclass's factory method.
* How can an object's instantiation be deferred to a subclass? Create an object by calling a factory method instead of directly calling a constructor.
This enables the creation of subclasses that can change the way in which an object is created (for example, by redefining which class to instantiate).
Definition
According to ''
Design Patterns: Elements of Reusable Object-Oriented Software'': "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses."
Creating an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information inaccessible to the composing object, may not provide a sufficient level of abstraction or may otherwise not be included in the composing object's
concerns. The factory method design pattern handles these problems by defining a separate
method
Method (, methodos, from μετά/meta "in pursuit or quest of" + ὁδός/hodos "a method, system; a way or manner" of doing, saying, etc.), literally means a pursuit of knowledge, investigation, mode of prosecuting such inquiry, or system. In re ...
for creating the objects, which subclasses can then override to specify the
derived type of product that will be created.
The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.
The pattern can also rely on the implementation of an
interface.
Structure
UML class 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
Creator
class that requires a
Product
object does not instantiate the
Product1
class directly. Instead, the
Creator
refers to a separate
factoryMethod()
to create a product object, which makes the
Creator
independent of the exact concrete class that is instantiated. Subclasses of
Creator
can redefine which class to instantiate. In this example, the
Creator1
subclass implements the abstract
factoryMethod()
by instantiating the
Product1
class.
Examples
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 ''
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.
import std;
enum class ProductId ;
// defines the interface of objects the factory method creates.
class Product ;
// implements the Product interface.
class ConcreteProductMINE: public Product ;
// implements the Product interface.
class ConcreteProductYOURS: public Product ;
// declares the factory method, which returns an object of type Product.
class Creator ;
int main()
The program output is like
this=0x6e5e90 print MINE
this=0x6e62c0 print YOURS
A maze game may be played in two modes, one with regular rooms that are only connected with adjacent rooms, and one with magic rooms that allow players to be transported at random.
Structure
Room
is the base class for a final product (
MagicRoom
or
OrdinaryRoom
).
MazeGame
declares the abstract factory method to produce such a base product.
MagicRoom
and
OrdinaryRoom
are subclasses of the base product implementing the final product.
MagicMazeGame
and
OrdinaryMazeGame
are subclasses of
MazeGame
implementing the factory method producing the final products. Factory methods thus decouple callers (
MazeGame
) from the implementation of the concrete classes. This makes the
new
operator redundant, allows adherence to the
open–closed principle and makes the final product more flexible in the event of change.
Example implementations
C#
// Empty vocabulary of actual object
public interface IPerson
public class Villager : IPerson
public class CityPerson : IPerson
public enum PersonType
///
/// Implementation of Factory - Used to create objects.
///
public class PersonFactory
The above code depicts the creation of an interface called
IPerson
and two implementations called
Villager
and
CityPerson
. Based on the type passed to the
PersonFactory
object, the original concrete object is returned as the interface
IPerson
.
A factory method is just an addition to the
PersonFactory
class. It creates the object of the class through interfaces but also allows the subclass to decide which class is instantiated.
public interface IProduct
public class Phone : IProduct
/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
public class PhoneConcreteFactory : ProductAbstractFactory
In this example,
MakeProduct
is used in
concreteFactory
. As a result,
MakeProduct()
may be invoked in order to retrieve it from the
IProduct
. Custom logic could run after the object is obtained in the concrete factory method.
GetObject
is made abstract in the factory interface.
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
This
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
example is similar to one in the book ''
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 ...
.''
The
MazeGame
uses
Room
but delegates the responsibility of creating
Room
objects to its subclasses that create the concrete classes. The regular game mode could use this template method:
public abstract class Room
public class MagicRoom extends Room
public class OrdinaryRoom extends Room
public abstract class MazeGame
The
MazeGame
constructor is a
template method that adds some common logic. It refers to the
makeRoom()
factory method that encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, the
makeRoom
method may be overridden:
public class MagicMazeGame extends MazeGame
public class OrdinaryMazeGame extends MazeGame
MazeGame ordinaryGame = new OrdinaryMazeGame();
MazeGame magicGame = new MagicMazeGame();
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
This
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
example shows interface implementations instead of subclassing (however, the same can be achieved through subclassing). The factory method can also be defined as
public
and called directly by the client code (in contrast to the previous Java example).
/* Factory and car interfaces */
interface CarFactory
interface Car
/* Concrete implementations of the factory and car */
class SedanFactory implements CarFactory
class Sedan implements Car
/* Client */
$factory = new SedanFactory();
$car = $factory->makeCar();
print $car->getType();
Python
This Python example employs the same as did the previous Java example.
from abc import ABC, abstractmethod
class MazeGame(ABC):
def __init__(self) -> None:
self.rooms = []
self._prepare_rooms()
def _prepare_rooms(self) -> None:
room1 = self.make_room()
room2 = self.make_room()
room1.connect(room2)
self.rooms.append(room1)
self.rooms.append(room2)
def play(self) -> None:
print(f"Playing using ")
@abstractmethod
def make_room(self):
raise NotImplementedError("You should implement this!")
class MagicMazeGame(MazeGame):
def make_room(self) -> "MagicRoom":
return MagicRoom()
class OrdinaryMazeGame(MazeGame):
def make_room(self) -> "OrdinaryRoom":
return OrdinaryRoom()
class Room(ABC):
def __init__(self) -> None:
self.connected_rooms = []
def connect(self, room: "Room") -> None:
self.connected_rooms.append(room)
class MagicRoom(Room):
def __str__(self) -> str:
return "Magic room"
class OrdinaryRoom(Room):
def __str__(self) -> str:
return "Ordinary room"
ordinaryGame = OrdinaryMazeGame()
ordinaryGame.play()
magicGame = MagicMazeGame()
magicGame.play()
Uses
* In
ADO.NETIDbCommand.CreateParameteris an example of the use of factory method to connect parallel class hierarchies.
* In
QtQMainWindow::createPopupMenu is a factory method declared in a framework that can be overridden in
application code
This glossary of computer science is a list of definitions of terms and concepts used in computer science, its sub-disciplines, and related fields, including terms relevant to software, data science, and .
A
...
.
* In
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, several factories are used in th
javax.xml.parserspackage, such as javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.
* In the
HTML5
HTML5 (Hypertext Markup Language 5) is a markup language used for structuring and presenting hypertext documents on the World Wide Web. It was the fifth and final major HTML version that is now a retired World Wide Web Consortium (W3C) recommend ...
DOM API
An application programming interface (API) is a connection between computers or between computer programs. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how to build ...
, the Document interface contains a createElement() factory method for creating specific elements of the HTMLElement interface.
See also
* ''
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 ...
'', the highly influential book
*
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" ...
, overview of design patterns in general
*
Abstract factory pattern
The abstract factory pattern in software engineering 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 that have a common theme w ...
, a pattern often implemented using factory methods
*
Builder pattern, another creational pattern
*
Template method pattern
In object-oriented programming, the template method is one of the behavioral pattern, behavioral Software design pattern, design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclas ...
, which may call factory methods
*
Joshua Bloch's idea of a
static factory method
Static may refer to:
Places
*Static Nunatak, in Antarctica
*Static, Kentucky and Tennessee, U.S.
*Static Peak, a mountain in Wyoming, U.S.
**Static Peak Divide, a mountain pass near the peak
Science and technology Physics
*Static electricity, a n ...
for which Bloch claims there is no direct equivalent 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 ...
''.
Notes
References
*
*
*
External links
Factory Design Pattern Implementation in Java
Factory method in UML and in LePUS3(a Design Description Language)
Consider static factory methodsby Joshua Bloch
{{DEFAULTSORT:Factory Method Pattern
Software design patterns
Articles with example Java code
Method (computer programming)
Articles with example C Sharp code
Articles with example PHP code