Jump to content
Wikipedia The Free Encyclopedia

Factory method pattern

From Wikipedia, the free encyclopedia
Object-oriented software design pattern

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 ]
A sample UML class diagram for the Factory Method design pattern. [4]

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? ]

importstd;
enumclassProductId{MINE,YOURS};
// defines the interface of objects the factory method creates.
classProduct{
public:
virtualvoidprint()=0;
virtual~Product()=default;
};
// implements the Product interface.
classConcreteProductMINE:publicProduct{
public:
voidprint(){
std::println("this={} print MINE",this);
}
};
// )implements the Product interface.
classConcreteProductYOURS:publicProduct{
public:
voidprint(){
std::println("this={} print YOURS",this);
}
};
// declares the factory method, which returns an object of type Product.
classCreator{
public:
virtualstd::unique_ptr<Product>create(ProductIdid){
if(ProductId::MINE==id)returnstd::make_unique<ConcreteProductMINE>();
if(ProductId::YOURS==id)returnstd::make_unique<ConcreteProductYOURS>();
// repeat for remaining products...
returnnullptr;
}
virtual~Creator()=default;
};
intmain(){
// 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=0x6e5e90printMINE
this=0x6e62c0printYOURS

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 ]

C#

[edit ]
// Empty vocabulary of actual object
publicinterfaceIPerson
{
stringGetName();
}
publicclassVillager:IPerson
{
publicstringGetName()
{
return"Village Person";
}
}
publicclassCityPerson:IPerson
{
publicstringGetName()
{
return"City Person";
}
}
publicenumPersonType
{
Rural,
Urban
}
/// <summary>
/// Implementation of Factory - Used to create objects.
/// </summary>
publicclassPersonFactory
{
publicIPersonGetPerson(PersonTypetype)
{
switch(type)
{
casePersonType.Rural:
returnnewVillager();
casePersonType.Urban:
returnnewCityPerson();
default:
thrownewNotSupportedException();
}
}
}

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.

publicinterfaceIProduct
{
stringGetName();
boolSetPrice(doubleprice);
}
publicclassPhone:IProduct
{
privatedouble_price;
publicstringGetName()
{
return"Apple TouchPad";
}
publicboolSetPrice(doubleprice)
{
_price=price;
returntrue;
}
}
/* Almost same as Factory, just an additional exposure to do something with the created method */
publicabstractclassProductAbstractFactory
{
protectedabstractIProductMakeProduct();
publicIProductGetObject()// Implementation of Factory Method.
{
returnthis.MakeProduct();
}
}
publicclassPhoneConcreteFactory:ProductAbstractFactory
{
protectedoverrideIProductMakeProduct()
{
IProductproduct=newPhone();
// Do something with the object after receiving it
product.SetPrice(20.30);
returnproduct;
}
}

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:

publicabstractclass Room{
abstractvoidconnect(Roomroom);
}
publicclass MagicRoomextendsRoom{
publicvoidconnect(Roomroom){}
}
publicclass OrdinaryRoomextendsRoom{
publicvoidconnect(Roomroom){}
}
publicabstractclass MazeGame{
privatefinalList<Room>rooms=newArrayList<>();
publicMazeGame(){
Roomroom1=makeRoom();
Roomroom2=makeRoom();
room1.connect(room2);
rooms.add(room1);
rooms.add(room2);
}
abstractprotectedRoommakeRoom();
}

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:

publicclass MagicMazeGameextendsMazeGame{
@Override
protectedMagicRoommakeRoom(){
returnnewMagicRoom();
}
}
publicclass OrdinaryMazeGameextendsMazeGame{
@Override
protectedOrdinaryRoommakeRoom(){
returnnewOrdinaryRoom();
}
}
MazeGameordinaryGame=newOrdinaryMazeGame();
MazeGamemagicGame=newMagicMazeGame();

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 publicand 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 ]

See also

[edit ]

Notes

[edit ]
  1. ^ Gamma et al. 1995, p. 107.
  2. ^ Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1995). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.
  3. ^ 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日.
  4. ^ "The Factory Method design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017年08月12日.
  5. ^ Gamma et al. 1995, p. 122.

References

[edit ]
[edit ]
The Wikibook Computer Science Design Patterns has a page on the topic of: Factory method examples
Gang of Four
patterns
Creational
Structural
Behavioral
Concurrency
patterns
Architectural
patterns
Other
patterns
Books
People
Communities
See also

AltStyle によって変換されたページ (->オリジナル) /