Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Factory method pattern

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

Inobject-oriented programming, thefactory method pattern is adesign pattern that uses factory methods to deal with the problem ofcreating objects without having to specify their exactclasses. Rather than by calling aconstructor, this is accomplished by invoking a factory method to create an object. Factory methods can be specified in aninterface and implemented by subclasses or implemented in a base class and optionallyoverridden by subclasses. It is one of the 23 classic design patterns described in the bookDesign Patterns (often referred to as the "Gang of Four" or simply "GoF") and is subcategorized as acreational pattern.[1]

Overview

[edit]

The factory method design pattern solves problems such as:

  • How can an object'ssubclasses redefine its subsequent and distinct implementation? The pattern involves creation of a factory method within thesuperclass 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 toDesign 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'sconcerns. The factory method design pattern handles these problems by defining a separatemethod for creating the objects, which subclasses can then override to specify thederived 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 aninterface.

Structure

[edit]

UML class diagram

[edit]
A sample UML class diagram for the Factory Method design pattern.[4]

In the aboveUMLclass diagram, theCreator class that requires aProduct object does not instantiate theProduct1 class directly. Instead, theCreator refers to a separatefactoryMethod() to create a product object, which makes theCreator independent of the exact concrete class that is instantiated. Subclasses ofCreator can redefine which class to instantiate. In this example, theCreator1 subclass implements the abstractfactoryMethod() by instantiating theProduct1 class.

Examples

[edit]

Structure

[edit]

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.

Room is the base class for a final product (MagicRoom orOrdinaryRoom).MazeGame declares the abstract factory method to produce such a base product.MagicRoom andOrdinaryRoom are subclasses of the base product implementing the final product.MagicMazeGame andOrdinaryMazeGame are subclasses ofMazeGame implementing the factory method producing the final products. Factory methods thus decouple callers (MazeGame) from the implementation of the concrete classes. This makes thenew operator redundant, allows adherence to theopen–closed principle and makes the final product more flexible in the event of change.

Example implementations

[edit]

C++

[edit]

ThisC++23 implementation is based on the pre C++98 implementation in theDesign Patterns book.[5]

importstd;usingstd::unique_ptr;enumclassProductId:char{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:virtualunique_ptr<Product>create(ProductIdid){switch(id){caseProductId::MINE:returnstd::make_unique<ConcreteProductMINE>();caseProductId::YOURS:returnstd::make_unique<ConcreteProductYOURS>();// repeat for remaining productsdefault:returnnullptr;}}virtual~Creator()=default;};intmain(intargc,char*argv[]){unique_ptr<Creator>creator=std::make_unique<Creator>();unique_ptr<Product>product=creator->create(ProductId::MINE);product->print();product=creator->create(ProductId::YOURS);product->print();}

The program output is like

this=0x6e5e90printMINEthis=0x6e62c0printYOURS

C#

[edit]
// Empty vocabulary of actual objectpublicinterfaceIPerson{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 calledIPerson and two implementations calledVillager andCityPerson. Based on the type passed to thePersonFactory object, the original concrete object is returned as the interfaceIPerson.

A factory method is just an addition to thePersonFactory 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 itproduct.SetPrice(20.30);returnproduct;}}

In this example,MakeProduct is used inconcreteFactory. As a result,MakeProduct() may be invoked in order to retrieve it from theIProduct. Custom logic could run after the object is obtained in the concrete factory method.GetObject is made abstract in the factory interface.

Java

[edit]

ThisJava example is similar to one in the bookDesign Patterns.

TheMazeGame usesRoom but delegates the responsibility of creatingRoom objects to its subclasses that create the concrete classes. The regular game mode could use this template method:

publicabstractclassRoom{abstractvoidconnect(Roomroom);}publicclassMagicRoomextendsRoom{publicvoidconnect(Roomroom){}}publicclassOrdinaryRoomextendsRoom{publicvoidconnect(Roomroom){}}publicabstractclassMazeGame{privatefinalList<Room>rooms=newArrayList<>();publicMazeGame(){Roomroom1=makeRoom();Roomroom2=makeRoom();room1.connect(room2);rooms.add(room1);rooms.add(room2);}abstractprotectedRoommakeRoom();}

TheMazeGame constructor is atemplate method that adds some common logic. It refers to themakeRoom() 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, themakeRoom method may be overridden:

publicclassMagicMazeGameextendsMazeGame{@OverrideprotectedMagicRoommakeRoom(){returnnewMagicRoom();}}publicclassOrdinaryMazeGameextendsMazeGame{@OverrideprotectedOrdinaryRoommakeRoom(){returnnewOrdinaryRoom();}}MazeGameordinaryGame=newOrdinaryMazeGame();MazeGamemagicGame=newMagicMazeGame();

PHP

[edit]

ThisPHP example shows interface implementations instead of subclassing (however, the same can be achieved through subclassing). The factory method can also be defined aspublicand called directly by the client code (in contrast to the previous Java example).

/* Factory and car interfaces */interfaceCarFactory{publicfunctionmakeCar():Car;}interfaceCar{publicfunctiongetType():string;}/* Concrete implementations of the factory and car */classSedanFactoryimplementsCarFactory{publicfunctionmakeCar():Car{returnnewSedan();}}classSedanimplementsCar{publicfunctiongetType():string{return'Sedan';}}/* Client */$factory=newSedanFactory();$car=$factory->makeCar();print$car->getType();

Python

[edit]

This Python example employs the same as did the previous Java example.

fromabcimportABC,abstractmethodclassMazeGame(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)defplay(self)->None:print(f"Playing using{self.rooms[0]}")@abstractmethoddefmake_room(self):raiseNotImplementedError("You should implement this!")classMagicMazeGame(MazeGame):defmake_room(self)->"MagicRoom":returnMagicRoom()classOrdinaryMazeGame(MazeGame):defmake_room(self)->"OrdinaryRoom":returnOrdinaryRoom()classRoom(ABC):def__init__(self)->None:self.connected_rooms=[]defconnect(self,room:"Room")->None:self.connected_rooms.append(room)classMagicRoom(Room):def__str__(self)->str:return"Magic room"classOrdinaryRoom(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. Retrieved2012-09-12.
  4. ^"The Factory Method design pattern - Structure and Collaboration".w3sDesign.com. Retrieved2017-08-12.
  5. ^Gamma et al. 1995, p. 122.

References

[edit]

External links

[edit]
The WikibookComputer 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
Retrieved from "https://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=1309372924"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp