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 class. Rather than by calling a constructor, this is done by calling a factory method to create an object. Factory methods can either be specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes. 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 sub-categorized as a creational pattern.
The Factory Method design pattern solves problems like:
The Factory Method design pattern describes how to solve such problems:
This enables the writing of subclasses that can change the way an object is created (e.g. by redefining which class to instantiate).
See also the UML class diagram below.
"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.[1] As shown in the C# example below, the factory method pattern can also rely on an Interface - in this case IPerson - to be implemented.
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 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.
This C++14 implementation is based on the pre C++98 implementation in the book.
enum ProductId ;
// defines the interface of objects the factory method creates.class Product ;
// implements the Product interface.class ConcreteProductMINE: public Product ;
// implements the Product interface.class ConcreteProductYOURS: public Product ;
// declares the factory method, which returns an object of type Product.class Creator ;
int main
The program output is like
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
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.
public class Villager : IPerson
public class CityPerson : IPerson
public enum PersonType
/// IPerson
and two implementations called Villager
and CityPerson
. Based on the type passed into the PersonFactory
object, we are returning the original concrete object as the interface IPerson
.
A factory method is just an addition to PersonFactory
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 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 : ProductAbstractFactoryYou 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.
This Java example is similar to one in the book Design Patterns.
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 class MagicRoom extends Room
public class OrdinaryRoom extends Room
public abstract class MazeGame
In the above snippet, the MazeGame
constructor is a template method 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 OrdinaryMazeGame extends MazeGame
MazeGame ordinaryGame = new OrdinaryMazeGame;MazeGame magicGame = new MagicMazeGame;
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).
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;
Same as Java example.
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 = OrdinaryMazeGameordinaryGame.play
magicGame = MagicMazeGamemagicGame.play