In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact 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.
Overview
The Factory Method
[1]
design pattern is one of the twenty-three well-known design patterns 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:
[2]
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)
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 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]
As shown in the C# example below, the factory method pattern can also rely on an Interface - in this case IPerson - to be implemented.
the Creator class that requires a Product object does not instantiate the Product1 class directly.
Instead, the Creator refers to a separate fact
which makes the Creator independent of which concrete class is instantiated.
Subclasseclass.
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.
// Empty vocabulary of actual objectpublicinterfaceIPersopublicstringGetName(){return"City Person";}}publicenumPersonType{Rural,Urban}/// <summary>/// Implementation of Factory - Used to create objects./// </summary>publicclassFactory{publicIPersonGetPerson(PersonTypetype){switch(type){casePersonType.Rural:returnnewVillager();caseboolSetPrice(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.{returnproduct;}}
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.
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 with the Java example above).
/* 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();
In Java, several factories are used in the javax.xml.parsers package. e.g. javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.
In the HTML5DOMAPI, the Document interface contains a createElement factory method for creating specific elements of the HTMLElement interface.
^Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 107ff. ISBN0-201-63361-2.{{cite book}}: CS1 maint: multiple names: authors list (link)