Factories: Separate Object Creation
An export procedure stays the same while its output format changes. Factory Method leaves an object-creation step replaceable by a subclass.
Call a creation method from shared work
class TextExporter:
def render(self, text):
return "TEXT: " + text
class ExportJob:
def create_exporter(self):
raise NotImplementedError
def run(self, text):
return self.create_exporter().render(text)
class TextExportJob(ExportJob):
def create_exporter(self):
return TextExporter()
print(TextExportJob().run("weekly report"))
The result is TEXT: weekly report. ExportJob owns the rendering procedure; TextExportJob chooses the exporter. Another subclass can override create_exporter to provide a different product.
Separate similar names
- Simple factory: A function chooses an object based on a value or condition. Useful, but not every creation helper is the Factory Method pattern.
- Factory Method: A subclass replaces a creation point used by a shared procedure.
- Abstract Factory: Creates a family of related objects, such as buttons and input fields from one theme.
In Python, passing a creation function may be enough. A single object does not necessarily justify a large class hierarchy.
Check your understanding
A light-theme button and light-theme input must be created together. Which factory purpose is closer?
Show explanation
Abstract Factory’s purpose of creating compatible product families. A small function or object may still be enough to preserve that consistency.