Factory method pattern: Difference between revisions
Continued removal of region sections as started in a previous edit. |
Tags: Mobile edit Mobile web edit |
||
(162 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{Short description|Object-oriented software design pattern}} |
|||
In [[class-based programming]], the '''factory method pattern''' is a [[creational pattern]] that uses factory methods to deal with the problem of [[object creation|creating objects]] without having to specify the exact [[class (computer programming)|class]] of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a [[Constructor (object-oriented programming)|constructor]]. |
|||
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 programming)|classes]]. Rather than by calling a [[Constructor (object-oriented programming)|constructor]], this is accomplished by invoking a factory method to create an object. Factory methods can be specified in an [[Interface (object-oriented programming)|interface]] and implemented by subclasses or implemented in a base class and optionally [[method overriding|overridden]] by subclasses. It is one of the 23 classic design patterns described in the book ''[[Design Patterns]]'' (often referred to as the "Gang of Four" or simply "GoF") and is subcategorized as a [[creational pattern]].{{sfn|Gamma|Helm|Johnson|Vlissides|1995|page=107}} |
|||
== |
==Overview== |
||
The factory method design pattern solves problems such as: |
|||
"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 (software)|Gang Of Four]]) |
|||
* How can an object's [[Subclass (computer science)|subclasses]] redefine its subsequent and distinct implementation? The pattern involves creation of a factory method within the [[Superclass (computer science)|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). |
|||
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 [[concern (computer science)|concerns]]. The factory method design pattern handles these problems by defining a separate [[method (computer science)|method]] for creating the objects, which [[subclass (computer science)|subclasses]] can then override to specify the [[Subtype|derived type]] of product that will be created. |
|||
==Definition== |
|||
The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.<ref>{{cite journal |
|||
According to ''[[Design Patterns|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."<ref name="gof">{{cite book |last1=Gamma |first1=Erich |author1-link=Erich Gamma |title=Design Patterns: Elements of Reusable Object-Oriented Software |title-link=Design Patterns |last2=Helm |first2=Richard |author2-link=Richard Helm |last3=Johnson |first3=Ralph |author3-link=Ralph Johnson (computer scientist) |last4=Vlissides |first4=John |author4-link=John Vlissides |publisher=Addison-Wesley |year=1995 |isbn=0-201-63361-2}}</ref> |
|||
| last1 = Freeman |
|||
| first1 = Eric |
|||
| last2 = Freeman |
|||
| first2 = Elisabeth |
|||
| last3 = Kathy |
|||
| first3 = Sierra |
|||
| last4 = Bert |
|||
| first4 = Bates |
|||
| editor-last1 = Hendrickson |
|||
| editor-first1 = Mike |
|||
| editor-last2 = Loukides |
|||
| editor-first2 = Mike |
|||
| year = 2004 |
|||
| title = Head First Design Patterns |
|||
| volume = 1 |
|||
| page = 162 |
|||
| publisher = O'REILLY |
|||
| format = paperback |
|||
| isbn = 978-0-596-00712-6 |
|||
| accessdate = 2012-09-12 |
|||
| url = http://shop.oreilly.com/product/9780596007126.do |
|||
}}</ref> |
|||
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 [[concern (computer science)|concerns]]. The factory method design pattern handles these problems by defining a separate [[method (computer science)|method]] for creating the objects, which subclasses can then override to specify the [[Subtyping|derived type]] of product that will be created. |
|||
== Example implementations == |
|||
The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects.<ref>{{cite book |last1=Freeman |first1=Eric |url=http://shop.oreilly.com/product/9780596007126.do |title=Head First Design Patterns: A Brain-Friendly Guide |last2=Robson |first2=Elisabeth |last3=Sierra |first3=Kathy |last4=Bates |first4=Bert |publisher=O'Reilly Media |year=2004 |isbn=978-0-596-00712-6 |editor-last1=Hendrickson |editor-first1=Mike |edition=1st |volume=1 |page=162 |format=paperback |access-date=2012-09-12 |editor-last2=Loukides |editor-first2=Mike}}</ref> |
|||
=== Java === |
|||
The pattern can also rely on the implementation of an [[Interface (object-oriented programming)|interface]]. |
|||
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 (this [[Java (programming language)|Java]] example is similar to one in the book ''[[Design Patterns]]''). The regular game mode could use this template method: |
|||
==Structure== |
|||
<source lang=Java> |
|||
public abstract class MazeGame { |
|||
private final List<Room> rooms = new ArrayList<>(); |
|||
=== UML class diagram === |
|||
public MazeGame() { |
|||
Room room1 = makeRoom(); |
|||
Room room2 = makeRoom(); |
|||
room1.connect(room2); |
|||
rooms.add(room1); |
|||
rooms.add(room2); |
|||
} |
|||
[[File:w3sDesign Factory Method Design Pattern UML.jpg|frame|none|A sample UML class diagram for the Factory Method design pattern. |
|||
abstract protected Room makeRoom(); |
|||
<ref>{{cite web|title=The Factory Method design pattern - Structure and Collaboration|url=http://w3sdesign.com/?gr=c03&ugr=struct|website=w3sDesign.com|access-date=2017-08-12}}</ref>]] |
|||
} |
|||
</source> |
|||
In the above [[Unified Modeling Language|UML]] [[class diagram]], the <code>Creator</code> class that requires a <code>Product</code> object does not instantiate the <code>Product1</code> class directly. Instead, the <code>Creator</code> refers to a separate <code>factoryMethod()</code> to create a product object, which makes the <code>Creator</code> independent of the exact concrete class that is instantiated. Subclasses of <code>Creator</code> can redefine which class to instantiate. In this example, the <code>Creator1</code> subclass implements the abstract <code>factoryMethod()</code> by instantiating the <code>Product1</code> class. |
|||
In the above snippet, the <code>MazeGame</code> constructor is a [[Template method pattern|template method]] that makes some common logic. It refers to the <code>makeRoom</code> 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 <code>makeRoom</code> method: |
|||
== Examples == |
|||
<source lang=Java> |
|||
This [[C++23]] implementation is based on the pre C++98 implementation in the book.{{sfn|Gamma|Helm|Johnson|Vlissides|1995|page=122}}{{Which one|date=August 2024}} |
|||
public class MagicMazeGame extends MazeGame { |
|||
<syntaxhighlight lang="c++"> |
|||
@Override |
|||
import std; |
|||
protected Room makeRoom() { |
|||
return new MagicRoom(); |
|||
} |
|||
} |
|||
enum class ProductId {MINE, YOURS}; |
|||
public class OrdinaryMazeGame extends MazeGame { |
|||
@Override |
|||
protected Room makeRoom() { |
|||
return new OrdinaryRoom(); |
|||
} |
|||
} |
|||
// defines the interface of objects the factory method creates. |
|||
MazeGame ordinaryGame = new OrdinaryMazeGame(); |
|||
class Product { |
|||
MazeGame magicGame = new MagicMazeGame(); |
|||
public: |
|||
</source> |
|||
virtual void print() = 0; |
|||
virtual ~Product() = default; |
|||
}; |
|||
// implements the Product interface. |
|||
=== Delphi/Object Pascal === |
|||
class ConcreteProductMINE: public Product { |
|||
A board game has two modes, Chess and Checkers, selectable by the user before the game starts. |
|||
public: |
|||
void print() { |
|||
std::println("this={} print MINE", this); |
|||
} |
|||
}; |
|||
// )implements the Product interface. |
|||
The generic board class, to be used as template for each board type: |
|||
class ConcreteProductYOURS: public Product { |
|||
<source lang=Delphi> |
|||
public: |
|||
TBoardGame = Class |
|||
void print() { |
|||
public |
|||
std::println("this={} print YOURS", this); |
|||
procedure makeBoard; Virtual; Abstract; |
|||
} |
|||
}; |
|||
</source> |
|||
// declares the factory method, which returns an object of type Product. |
|||
The specific board classes: |
|||
class Creator { |
|||
<source lang=Delphi> |
|||
public: |
|||
TChessGame = Class (TBoardGame) |
|||
virtual std::unique_ptr<Product> create(ProductId id) { |
|||
public |
|||
if (ProductId::MINE == id) return std::make_unique<ConcreteProductMINE>(); |
|||
procedure makeBoard; Override; |
|||
if (ProductId::YOURS == id) return std::make_unique<ConcreteProductYOURS>(); |
|||
End; |
|||
// repeat for remaining products... |
|||
return nullptr; |
|||
TCheckersGame = Class (TBoardGame) |
|||
} |
|||
virtual ~Creator() = default; |
|||
procedure makeBoard; Override; |
|||
}; |
|||
End; |
|||
</source> |
|||
int main() { |
|||
And the factory class: |
|||
// The unique_ptr prevent memory leaks. |
|||
<source lang=Delphi> |
|||
std::unique_ptr<Creator> creator = std::make_unique<Creator>(); |
|||
// Interface |
|||
std::unique_ptr<Product> product = creator->create(ProductId::MINE); |
|||
TBoardGamesFactory = Class |
|||
product->print(); |
|||
public |
|||
class function CreateBoardGame(GameType: TBoardGameType): TBoardGame; |
|||
End; |
|||
product = creator->create(ProductId::YOURS); |
|||
// Implementation |
|||
product->print(); |
|||
class function TBoardGamesFactory.CreateBoardGame(GameType: TBoardGameType): TBoardGame; |
|||
begin |
|||
case GameType of |
|||
bgChess : Result := TChessGame.Create; |
|||
bgCheckers: Result := TCheckersGame.Create; |
|||
end; |
|||
end; |
|||
</source> |
|||
Would be instantiated like this: |
|||
<source lang=Delphi> |
|||
var |
|||
Game: TBoardGame; |
|||
begin |
|||
Game := TBoardGamesFactory.CreateBoardGame(bgCheckers); // This TBoardGame variable will in fact be a TCheckersGame, created by the factory |
|||
Game.makeBoard; |
|||
</source> |
|||
=== PHP === |
|||
Another example in PHP 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 the Java example above). |
|||
<source lang=PHP> |
|||
/* Factory and car interfaces */ |
|||
interface CarFactory |
|||
{ |
|||
public function makeCar(); |
|||
} |
} |
||
</syntaxhighlight> |
|||
The program output is like |
|||
interface Car |
|||
{ |
|||
public function getType(); |
|||
} |
|||
<syntaxhighlight lang="c++"> |
|||
/* Concrete implementations of the factory and car */ |
|||
this=0x6e5e90 print MINE |
|||
this=0x6e62c0 print YOURS |
|||
</syntaxhighlight> |
|||
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. |
|||
class SedanFactory implements CarFactory |
|||
{ |
|||
public function makeCar() |
|||
{ |
|||
return new Sedan(); |
|||
} |
|||
} |
|||
=== Structure === |
|||
class Sedan implements Car |
|||
[[File:New WikiFactoryMethod.png|734x734px|center]] |
|||
{ |
|||
public function getType() |
|||
{ |
|||
return 'Sedan'; |
|||
} |
|||
} |
|||
<code>Room</code> is the base class for a final product (<code>MagicRoom</code> or <code>OrdinaryRoom</code>). <code>MazeGame</code> declares the abstract factory method to produce such a base product. <code>MagicRoom</code> and <code>OrdinaryRoom</code> are subclasses of the base product implementing the final product. <code>MagicMazeGame</code> and <code>OrdinaryMazeGame</code> are subclasses of <code>MazeGame</code> implementing the factory method producing the final products. Factory methods thus decouple callers (<code>MazeGame</code>) from the implementation of the concrete classes. This makes the <code>new</code> operator redundant, allows adherence to the [[open–closed principle]] and makes the final product more flexible in the event of change. |
|||
/* Client */ |
|||
$factory = new SedanFactory(); |
|||
$car = $factory->makeCar(); |
|||
print $car->getType(); |
|||
</source> |
|||
=== |
=== Example implementations === |
||
====[[C Sharp (programming language)|C#]]==== |
|||
Factory pattern deals with the instantiation of object without exposing the instantiation logic. In other words, a Factory is actually a creator of objects which have a common interface. |
|||
< |
<syntaxhighlight lang="csharp"> |
||
//Empty vocabulary of |
// Empty vocabulary of actual object |
||
public interface |
public interface IPerson |
||
{ |
{ |
||
string GetName(); |
string GetName(); |
||
} |
} |
||
public class |
public class Villager : IPerson |
||
{ |
{ |
||
public string GetName() |
public string GetName() |
||
Line 182: | Line 112: | ||
} |
} |
||
public class |
public class CityPerson : IPerson |
||
{ |
{ |
||
public string GetName() |
public string GetName() |
||
Line 190: | Line 120: | ||
} |
} |
||
public enum |
public enum PersonType |
||
{ |
{ |
||
Rural, |
Rural, |
||
Line 197: | Line 127: | ||
/// <summary> |
/// <summary> |
||
/// Implementation of Factory - Used to create objects |
/// Implementation of Factory - Used to create objects. |
||
/// </summary> |
/// </summary> |
||
public class |
public class PersonFactory |
||
{ |
{ |
||
public |
public IPerson GetPerson(PersonType type) |
||
{ |
{ |
||
switch (type) |
switch (type) |
||
{ |
{ |
||
case |
case PersonType.Rural: |
||
return new |
return new Villager(); |
||
case |
case PersonType.Urban: |
||
return new |
return new CityPerson(); |
||
default: |
default: |
||
throw new NotSupportedException(); |
throw new NotSupportedException(); |
||
Line 214: | Line 144: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</source> |
|||
The above code depicts the creation of an interface called <code>IPerson</code> and two implementations called <code>Villager</code> and <code>CityPerson</code>. Based on the type passed to the <code>PersonFactory</code> object, the original concrete object is returned as the interface <code>IPerson</code>. |
|||
A |
A factory method is just an addition to the <code>PersonFactory</code> class. It creates the object of the class through interfaces but also allows the subclass to decide which class is instantiated. |
||
< |
<syntaxhighlight lang="csharp"> |
||
public interface IProduct |
public interface IProduct |
||
{ |
{ |
||
string GetName(); |
string GetName(); |
||
bool SetPrice(double price); |
|||
} |
} |
||
public class Phone : IProduct |
public class Phone : IProduct |
||
{ |
{ |
||
private double _price; |
private double _price; |
||
Line 235: | Line 165: | ||
} |
} |
||
public |
public bool SetPrice(double price) |
||
{ |
{ |
||
_price = price; |
|||
return |
return true; |
||
} |
} |
||
} |
} |
||
Line 245: | Line 175: | ||
public abstract class ProductAbstractFactory |
public abstract class ProductAbstractFactory |
||
{ |
{ |
||
protected abstract IProduct |
protected abstract IProduct MakeProduct(); |
||
public IProduct GetObject() // Implementation of Factory Method. |
public IProduct GetObject() // Implementation of Factory Method. |
||
{ |
{ |
||
return this. |
return this.MakeProduct(); |
||
} |
} |
||
} |
} |
||
Line 255: | Line 185: | ||
public class PhoneConcreteFactory : ProductAbstractFactory |
public class PhoneConcreteFactory : ProductAbstractFactory |
||
{ |
{ |
||
protected override IProduct |
protected override IProduct MakeProduct() |
||
{ |
{ |
||
IProduct product = new Phone(); |
IProduct product = new Phone(); |
||
//Do something with the object after |
// Do something with the object after receiving it |
||
product.SetPrice(20.30); |
product.SetPrice(20.30); |
||
return product; |
return product; |
||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</source> |
|||
In this example, <code>MakeProduct</code> is used in <code>concreteFactory</code>. As a result, <code>MakeProduct()</code> may be invoked in order to retrieve it from the <code>IProduct</code>. Custom logic could run after the object is obtained in the concrete factory method. <code>GetObject</code> is made abstract in the factory interface. |
|||
====[[Java (programming language)|Java]]==== |
|||
==Limitations== |
|||
This [[Java (programming language)|Java]] example is similar to one in the book ''[[Design Patterns]].'' |
|||
There are three limitations associated with the use of the factory method. The first relates to [[code refactoring|refactoring]] existing code; the other two relate to extending a class. |
|||
[[File:Maze game UML.svg]] |
|||
* 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:<source lang=Java>Complex c = new Complex(-1, 0);</source> |
|||
The <code>MazeGame</code> uses <code>Room</code> but delegates the responsibility of creating <code>Room</code> objects to its subclasses that create the concrete classes. The regular game mode could use this template method: |
|||
:Once we realize that two different factories are needed, we change the class (to the code shown [[Factory (object-oriented programming)#Java|earlier]]). But since the constructor is now private, the existing client code no longer compiles. |
|||
<syntaxhighlight lang="java"> |
|||
* 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. |
|||
public abstract class Room { |
|||
* 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 <code>StrangeComplex</code> extends <code>Complex</code>, then unless <code>StrangeComplex</code> provides its own version of all factory methods, the call <source lang=Java>StrangeComplex.fromPolar(1, pi);</source> will yield an instance of <code>Complex</code> (the superclass) rather than the expected instance of the subclass. The reflection features of some languages can avoid this issue. |
|||
abstract void connect(Room room); |
|||
} |
|||
public class MagicRoom extends Room { |
|||
All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also [[Virtual class]]).<ref>{{cite journal |
|||
public void connect(Room room) {} |
|||
| first = Ellen |
|||
} |
|||
| last = Agerbo |
|||
| first2 = Aino |
|||
public class OrdinaryRoom extends Room { |
|||
| last2 = Cornils |
|||
public void connect(Room room) {} |
|||
| isbn = 1-58113-005-8 |
|||
} |
|||
| title = How to preserve the benefits of design patterns |
|||
| pages = 134–143 |
|||
public abstract class MazeGame { |
|||
| year = 1998 |
|||
private final List<Room> rooms = new ArrayList<>(); |
|||
| journal = Conference on Object Oriented Programming Systems Languages and Applications |
|||
| location = Vancouver, British Columbia, Canada |
|||
public MazeGame() { |
|||
| publisher = ACM |
|||
Room room1 = makeRoom(); |
|||
}}</ref> |
|||
Room room2 = makeRoom(); |
|||
room1.connect(room2); |
|||
rooms.add(room1); |
|||
rooms.add(room2); |
|||
} |
|||
abstract protected Room makeRoom(); |
|||
} |
|||
</syntaxhighlight> |
|||
The <code>MazeGame</code> constructor is a [[Template method pattern|template method]] that adds some common logic. It refers to the <code>makeRoom()</code> 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 <code>makeRoom</code> method may be overridden: |
|||
<syntaxhighlight lang="java"> |
|||
public class MagicMazeGame extends MazeGame { |
|||
@Override |
|||
protected MagicRoom makeRoom() { |
|||
return new MagicRoom(); |
|||
} |
|||
} |
|||
public class OrdinaryMazeGame extends MazeGame { |
|||
@Override |
|||
protected OrdinaryRoom makeRoom() { |
|||
return new OrdinaryRoom(); |
|||
} |
|||
} |
|||
MazeGame ordinaryGame = new OrdinaryMazeGame(); |
|||
MazeGame magicGame = new MagicMazeGame(); |
|||
</syntaxhighlight> |
|||
====[[PHP]]==== |
|||
This [[PHP]] example shows interface implementations instead of subclassing (however, the same can be achieved through subclassing). The factory method can also be defined as <code>public</code>and called directly by the client code (in contrast to the previous Java example). |
|||
<syntaxhighlight lang="php"> |
|||
/* Factory and car interfaces */ |
|||
interface CarFactory |
|||
{ |
|||
public function makeCar(): Car; |
|||
} |
|||
interface Car |
|||
{ |
|||
public function getType(): string; |
|||
} |
|||
/* Concrete implementations of the factory and car */ |
|||
class SedanFactory implements CarFactory |
|||
{ |
|||
public function makeCar(): Car |
|||
{ |
|||
return new Sedan(); |
|||
} |
|||
} |
|||
class Sedan implements Car |
|||
{ |
|||
public function getType(): string |
|||
{ |
|||
return 'Sedan'; |
|||
} |
|||
} |
|||
/* Client */ |
|||
$factory = new SedanFactory(); |
|||
$car = $factory->makeCar(); |
|||
print $car->getType(); |
|||
</syntaxhighlight> |
|||
==== [[Python (programming language)|Python]] ==== |
|||
This Python example employs the same as did the previous Java example. |
|||
<syntaxhighlight lang="python3"> |
|||
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 {self.rooms[0]}") |
|||
@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() |
|||
</syntaxhighlight> |
|||
==Uses== |
==Uses== |
||
* In [[ADO.NET]], [ |
* In [[ADO.NET]], [https://docs.microsoft.com/en-us/dotnet/api/system.data.idbcommand.createparameter?view=netframework-4.8 IDbCommand.CreateParameter] is an example of the use of factory method to connect parallel class hierarchies. |
||
* In [[Qt (toolkit)|Qt]], [http://qt-project.org/doc/qt-5.0/qtwidgets/qmainwindow.html#createPopupMenu QMainWindow::createPopupMenu] is a factory method declared in a framework that can be overridden in application code. |
* In [[Qt (toolkit)|Qt]], [http://qt-project.org/doc/qt-5.0/qtwidgets/qmainwindow.html#createPopupMenu QMainWindow::createPopupMenu] {{Webarchive|url=https://web.archive.org/web/20150719014739/http://qt-project.org/doc/qt-5.0/qtwidgets/qmainwindow.html#createPopupMenu |date=2015-07-19 }} is a factory method declared in a framework that can be overridden in [[application code]]. |
||
* In [[Java (programming language)|Java]], several factories are used in the [http://download.oracle.com/javase/1.5.0/docs/enwiki/api/javax/xml/parsers/package-summary.html javax.xml.parsers] package |
* In [[Java (programming language)|Java]], several factories are used in the [http://download.oracle.com/javase/1.5.0/docs/enwiki/api/javax/xml/parsers/package-summary.html javax.xml.parsers] package, such as javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory. |
||
* In the [[HTML5]] [[Document Object Model|DOM]] [[application programming interface|API]], the Document interface contains a createElement() factory method for creating specific elements of the HTMLElement interface. |
|||
==See also== |
==See also== |
||
Line 301: | Line 368: | ||
* [[Builder pattern]], another creational pattern |
* [[Builder pattern]], another creational pattern |
||
* [[Template method pattern]], which may call factory methods |
* [[Template method pattern]], which may call factory methods |
||
* [[Joshua Bloch]]'s idea of a |
* [[Joshua Bloch]]'s idea of a [[static factory method]] for which Bloch claims there is no direct equivalent in ''[[Design Patterns]]''. |
||
== |
==Notes== |
||
{{Reflist}} |
{{Reflist}} |
||
==References== |
|||
*{{cite book |
*{{cite book |
||
| author1= |
| author1=Martin Fowler | author2-link=Kent Beck | author2=Kent Beck | author3-link=John Brant (author) | author3=John Brant | author4-link=William Opdyke | author4=William Opdyke | author5-link=Don Roberts (author) | author5=Don Roberts |
||
| title = |
| title = Refactoring: Improving the Design of Existing Code |
||
| publisher = Addison-Wesley |
| publisher = Addison-Wesley |
||
| date=June 1999 |
| date=June 1999 |
||
| isbn = 0-201-48567-2 |
| isbn = 0-201-48567-2 |
||
| author1-link=Martin Fowler (software engineer) }} |
|||
}} |
|||
*{{cite book | |
*{{cite book |author1=Cox, Brad J. | |
||
title=Object-oriented programming: an evolutionary approach | |
|||
author=[[Erich Gamma|Gamma, Erich]]; [[Richard Helm|Helm, Richard]]; Johnson, Ralph; Vlissides, John | |
|||
title=[[Design Patterns|Design Patterns: Elements of Reusable Object-Oriented Software]] | |
|||
publisher=Addison-Wesley | |
|||
year=1994 | |
|||
isbn=0-201-63361-2 |
|||
}} |
|||
*{{cite book | |
|||
author=Cox, Brad J.; | |
|||
title=[[Object-oriented programming|Object-oriented programming: an evolutionary approach]] | |
|||
publisher=Addison-Wesley | |
publisher=Addison-Wesley | |
||
year=1986 | |
year=1986 | |
||
isbn=978-0-201-10393-9 |
isbn=978-0-201-10393-9 |
||
| |
|||
title-link=Object-oriented programming }} |
|||
*{{cite journal | |
*{{cite journal | |
||
last=Cohen | |
last=Cohen | |
||
Line 331: | Line 392: | ||
title=Better Construction with Factories | |
title=Better Construction with Factories | |
||
journal=Journal of Object Technology | |
journal=Journal of Object Technology | |
||
volume=6 | |
|||
issue=6 | |
|||
pages=103 | |
|||
year=2007 | |
year=2007 | |
||
publisher=[[Bertrand Meyer]] | |
publisher=[[Bertrand Meyer]] | |
||
url=http://tal.forum2.org/enwiki/static/cv/Factories.pdf | |
url=http://tal.forum2.org/enwiki/static/cv/Factories.pdf | |
||
access-date=2007-03-12 |
|||
| |
|||
doi=10.5381/jot.2007.6.6.a3 | |
|||
}} |
|||
doi-access=free }} |
|||
==External links== |
==External links== |
||
Line 343: | Line 408: | ||
| 2 = Factory method examples |
| 2 = Factory method examples |
||
}} |
}} |
||
* [http://designpattern.co.il/Factory.html Factory Design Pattern] {{Webarchive|url=https://web.archive.org/web/20180110103637/http://designpattern.co.il/Factory.html |date=2018-01-10 }} Implementation in Java |
|||
* [http://www.lepus.org.uk/ref/companion/FactoryMethod.xml Factory method in UML and in LePUS3] (a Design Description Language) |
|||
* [https://web.archive.org/web/20080503082912/http://www.lepus.org.uk/ref/companion/FactoryMethod.xml Factory method in UML and in LePUS3] (a Design Description Language) |
|||
* [http://drdobbs.com/java/208403883 Consider static factory methods] by Joshua Bloch |
* [http://drdobbs.com/java/208403883 Consider static factory methods] by Joshua Bloch |
||
* [http://markokrstic.net/factory-method-design-pattern-and-magento/ Factory Method and Magento] |
|||
{{Design Patterns Patterns}} |
{{Design Patterns Patterns}} |
Latest revision as of 22:08, 26 December 2024
In object-oriented programming, the factory method pattern is a design pattern 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 (often referred to as the "Gang of Four" or simply "GoF") and is subcategorized as a creational pattern.[1]
Overview
[edit]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
[edit]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."[2]
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 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.[3] The pattern can also rely on the implementation of an interface.
Structure
[edit]UML class diagram
[edit]In the above UML class diagram, 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
[edit]This C++23 implementation is based on the pre C++98 implementation in the book.[5][which?]
import std;
enum class ProductId {MINE, YOURS};
// defines the interface of objects the factory method creates.
class Product {
public:
virtual void print() = 0;
virtual ~Product() = default;
};
// implements the Product interface.
class ConcreteProductMINE: public Product {
public:
void print() {
std::println("this={} print MINE", this);
}
};
// )implements the Product interface.
class ConcreteProductYOURS: public Product {
public:
void print() {
std::println("this={} print YOURS", this);
}
};
// declares the factory method, which returns an object of type Product.
class Creator {
public:
virtual std::unique_ptr<Product> create(ProductId id) {
if (ProductId::MINE == id) return std::make_unique<ConcreteProductMINE>();
if (ProductId::YOURS == id) return std::make_unique<ConcreteProductYOURS>();
// repeat for remaining products...
return nullptr;
}
virtual ~Creator() = default;
};
int main() {
// The unique_ptr prevent memory leaks.
std::unique_ptr<Creator> creator = std::make_unique<Creator>();
std::unique_ptr<Product> product = creator->create(ProductId::MINE);
product->print();
product = creator->create(ProductId::YOURS);
product->print();
}
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
[edit]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
[edit]// Empty vocabulary of actual object
public interface IPerson
{
string GetName();
}
public class Villager : IPerson
{
public string GetName()
{
return "Village Person";
}
}
public class CityPerson : IPerson
{
public string GetName()
{
return "City Person";
}
}
public enum PersonType
{
Rural,
Urban
}
/// <summary>
/// Implementation of Factory - Used to create objects.
/// </summary>
public class PersonFactory
{
public IPerson GetPerson(PersonType type)
{
switch (type)
{
case PersonType.Rural:
return new Villager();
case PersonType.Urban:
return new CityPerson();
default:
throw new NotSupportedException();
}
}
}
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
{
string GetName();
bool SetPrice(double price);
}
public class Phone : IProduct
{
private double _price;
public string GetName()
{
return "Apple TouchPad";
}
public bool SetPrice(double price)
{
_price = price;
return true;
}
}
/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
{
protected abstract IProduct MakeProduct();
public IProduct GetObject() // Implementation of Factory Method.
{
return this.MakeProduct();
}
}
public class PhoneConcreteFactory : ProductAbstractFactory
{
protected override IProduct MakeProduct()
{
IProduct product = new Phone();
// Do something with the object after receiving it
product.SetPrice(20.30);
return product;
}
}
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.
This Java example is similar to one in the book Design Patterns.
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 {
abstract void connect(Room room);
}
public class MagicRoom extends Room {
public void connect(Room room) {}
}
public class OrdinaryRoom extends Room {
public void connect(Room room) {}
}
public abstract class MazeGame {
private final List<Room> rooms = new ArrayList<>();
public MazeGame() {
Room room1 = makeRoom();
Room room2 = makeRoom();
room1.connect(room2);
rooms.add(room1);
rooms.add(room2);
}
abstract protected Room makeRoom();
}
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 {
@Override
protected MagicRoom makeRoom() {
return new MagicRoom();
}
}
public class OrdinaryMazeGame extends MazeGame {
@Override
protected OrdinaryRoom makeRoom() {
return new OrdinaryRoom();
}
}
MazeGame ordinaryGame = new OrdinaryMazeGame();
MazeGame magicGame = new MagicMazeGame();
This PHP 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
{
public function makeCar(): Car;
}
interface Car
{
public function getType(): string;
}
/* Concrete implementations of the factory and car */
class SedanFactory implements CarFactory
{
public function makeCar(): Car
{
return new Sedan();
}
}
class Sedan implements Car
{
public function getType(): string
{
return 'Sedan';
}
}
/* Client */
$factory = new SedanFactory();
$car = $factory->makeCar();
print $car->getType();
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 {self.rooms[0]}")
@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
[edit]- In ADO.NET, IDbCommand.CreateParameter is an example of the use of factory method to connect parallel class hierarchies.
- In Qt, QMainWindow::createPopupMenu Archived 2015-07-19 at the Wayback Machine is a factory method declared in a framework that can be overridden in application code.
- In Java, several factories are used in the javax.xml.parsers package, such as javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.
- In the HTML5 DOM API, the Document interface contains a createElement() factory method for creating specific elements of the HTMLElement interface.
See also
[edit]- Design Patterns, the highly influential book
- Design pattern, overview of design patterns in general
- Abstract factory pattern, a pattern often implemented using factory methods
- Builder pattern, another creational pattern
- Template method pattern, which may call factory methods
- Joshua Bloch's idea of a static factory method for which Bloch claims there is no direct equivalent in Design Patterns.
Notes
[edit]- ^ Gamma et al. 1995, p. 107.
- ^ Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.
- ^ Freeman, Eric; Robson, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns: A Brain-Friendly Guide (paperback). Vol. 1 (1st ed.). O'Reilly Media. p. 162. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
- ^ "The Factory Method design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
- ^ Gamma et al. 1995, p. 122.
References
[edit]- Martin Fowler; Kent Beck; John Brant; William Opdyke; Don Roberts (June 1999). Refactoring: Improving the Design of Existing Code. Addison-Wesley. ISBN 0-201-48567-2.
- Cox, Brad J. (1986). Object-oriented programming: an evolutionary approach. Addison-Wesley. ISBN 978-0-201-10393-9.
- Cohen, Tal; Gil, Joseph (2007). "Better Construction with Factories" (PDF). Journal of Object Technology. 6 (6). Bertrand Meyer: 103. doi:10.5381/jot.2007.6.6.a3. Retrieved 2007-03-12.
External links
[edit]- Factory Design Pattern Archived 2018-01-10 at the Wayback Machine Implementation in Java
- Factory method in UML and in LePUS3 (a Design Description Language)
- Consider static factory methods by Joshua Bloch