Factory Method
Also known as "Virtual Constructor". This pattern defines a common interface for creating objects in a superclass, allowing subclasses to change the type of objects being created.
Note
The pattern is applicable when the program has a hierarchy of product classes.
Pattern structure
The participants classes in this pattern are:
Product
defines the interface for objects the factory method creates.ConcreteProduct
implements theProduct
interface.Creator
(also referred asFactory
because it creates the Product objects) declares the methodfactory_method
, which returns aProduct
object. May call the generating method for creatingProduct
objectsConcreteCreator
overrides the generating method for creatingConcreteProduct
objects.
---
title: Factory Method
---
classDiagram
direction TD
%% Defining relationships between classes
Creator <|-- ConcreteCreatorA
Creator <|-- ConcreteCreatorB
Product <|.. ConcreteProductA
Product <|.. ConcreteProductB
Creator ..> Product
%% Notes
note for Creator """def some_operation(self):
product = self.factory_method()
result = product.do_something()
return result
"""
note for ConcreteCreatorA "return ConcreteProductA()"
note for ConcreteCreatorB "return ConcreteProductB()"
%% Defining classes
class Creator{
...
+some_operation()
+factory_method()* Product
}
class ConcreteCreatorA{
...
+factory_method() Product
}
class ConcreteCreatorB{
...
+factory_method() Product
}
class Product{
<<interface>>
...
+do_something()*
}
class ConcreteProductA{
...
+do_something()
}
class ConcreteProductB{
...
+do_something()
}