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 ...
, the factory method pattern is a
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 ...
that uses factory methods to deal with the problem of
creating objects without having to specify the exact
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 ...
of the object that will be created. This is done by creating objects by calling a factory method—either specified in an
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 ...
and implemented by child classes, or implemented in a base class and optionally
overridden by derived classes—rather than by calling 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 ...
.
Overview
The Factory Method
design pattern is one of the twenty-three well-known ''
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 ...
'' 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 Factory Method design pattern solves problems like:
* How can an object be created so that subclasses can redefine which class to instantiate?
* How can a class defer instantiation to subclasses?
The Factory Method design pattern describes how to solve such problems:
* Define a separate operation (''factory method'') for creating an object.
* Create an object by calling a ''factory method''.
This enables writing of subclasses to change the way an object is created (to redefine which class to instantiate).
See also the UML class diagram below.
Definition
"Define an interface for creating an object, but let subclasses decide which class to instantiate. The Factory method lets a class defer instantiation it uses to subclasses." (
Gang Of Four
The Gang of Four () was a Maoist political faction composed of four Chinese Communist Party (CCP) officials. They came to prominence during the Cultural Revolution (1966–1976) and were later charged with a series of treasonous crimes. The ...
)
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 not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's
concerns. The factory method design pattern handles these problems by defining a separate
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 creating the objects, which
subclasses
Subclass may refer to:
* Subclass (taxonomy), a taxonomic rank below "class"
* Subclass (computer science)
* Subclass (set theory)
See also
* Superclass
{{disambiguation ...
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.
As shown in the C# example below, the factory method pattern can also rely on an Interface - in this case IPerson - to be implemented.
Structure
UML class 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
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 which concrete class 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.
Example
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. Thus factory methods 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 Factory
In the above code you can see the creation of one interface called
IPerson
and two implementations called
Villager
and
CityPerson
. Based on the type passed into the
Factory
object, we are returning the original concrete object as the interface
IPerson
.
A factory method is just an addition to
Factory
class. It creates the object of the class through interfaces but on the other hand, it also lets the subclass 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
You can see we have used
MakeProduct
in concreteFactory. As a result, you can easily call
MakeProduct()
from it to get the
IProduct
. You might also write your custom logic after getting the object in the concrete Factory Method. The GetObject is made abstract in the Factory interface.
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
This
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
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 Rooms but it puts the responsibility of creating Rooms to its subclasses which 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
In the above snippet, the
MazeGame
constructor is a
template method
In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book ''Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defines ...
that makes 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, it suffices to override the
makeRoom
method:
public class MagicMazeGame extends MazeGame
public class OrdinaryMazeGame extends MazeGame
MazeGame ordinaryGame = new OrdinaryMazeGame();
MazeGame magicGame = new MagicMazeGame();
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
Another example in
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
follows, this time using interface implementations as opposed to subclassing (however, the same can be achieved through subclassing). It is important to note that the factory method can also be defined as public and called directly by the client code (in contrast with the Java example above).
/* 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
Same as 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::createPopupMenuis a factory method declared in a framework that can be overridden in
application code
This glossary of computer software terms lists the general terms related to computer software, and related fields, as commonly used in Wikipedia articles.
Glossary
See also
* Outline of computer programming
* Outline of softw ...
.
* In
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, several factories are used in th
javax.xml.parserspackage. e.g. javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.
* In the
HTML5
HTML5 is a markup language used for structuring and presenting content on the World Wide Web. It is the fifth and final major HTML version that is a World Wide Web Consortium (W3C) recommendation. The current specification is known as the HT ...
DOM API
An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how ...
, 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" b ...
, overview of design patterns in general
*
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 ...
, a pattern often implemented using factory methods
*
Builder pattern The builder pattern is a design pattern designed to provide a flexible solution to various object creation problems in object-oriented programming. The intent of the Builder design pattern is to separate the construction of a complex object from it ...
, another creational pattern
*
Template method pattern
In object-oriented programming, the template method is one of the behavioral design patterns identified by Gamma et al. in the book '' Design Patterns''. The template method is a method in a superclass, usually an abstract superclass, and defin ...
, which may call factory methods
*
Joshua Bloch
Joshua J. Bloch (born August 28, 1961) is an American software engineer and a technology author, formerly employed at Sun Microsystems and Google. He led the design and implementation of numerous Java platform features, including the Java Collec ...
's idea of a ''
static factory method
Static may refer to:
Places
*Static Nunatak, a nunatak in Antarctica
United States
* Static, Kentucky and Tennessee
* Static Peak, a mountain in Wyoming
**Static Peak Divide, a mountain pass near the peak
Science and technology Physics
*Static e ...
'', which he says has 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 ...
''.
References
*
*
*
*
External links
Factory Design PatternImplementation 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