Mr. Latte


Lesson 5 of 13

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

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.

Looking for a product partner? Founders, teams, businesses: from problem framing to launch.