cconnected.
Understand the pattern. Find your own way.Find your starting point
Your learning feed/Idea 169 of 218
Ideas this builds on
Low-level design169 / 218

Factory Method: let a subtype choose construction

Picture

An exporter creates a formatter, formats records, and returns text. Its subclass chooses which formatter gets created.

Predict

What is the variation point in this creator?

Walk through the small example

Which formatter it constructs. The created product keeps the shared formatting contract.

Mental model and complete Python solution

Exporter.export is the shared workflow; TextExporter overrides make_formatter. A creation hook can combine naturally with Template Method. When variation is selected per request rather than per subtype, constructor injection or a callable factory may be clearer.

What the function promises: Export string records as text. No files are created.

from abc import ABC, abstractmethod

class TextFormatter:
    def format(self, records):
        return "\n".join(records)

class Exporter(ABC):
    @abstractmethod
    def make_formatter(self):
        pass
    def export(self, records):
        return self.make_formatter().format(records)

class TextExporter(Exporter):
    def make_formatter(self):
        return TextFormatter()

assert TextExporter().export(["a", "b"]) == "a\nb"
assert TextExporter().export([]) == ""

Work and storage: O(output length) formatting.

When to recognize it: Simple factory selects by configuration. Factory Method uses a subclass hook. Abstract Factory provides a compatible set of products.

Check before applying it: A factory method should not create subclasses where simple injection would express the choice clearly.

Change one rule

A caller chooses a formatter independently for every call. Must every choice be a subclass?

See what changes

No. Passing a formatter or callable factory may better express runtime variation. Match construction structure to the actual lifecycle.

Connect

Template Method: fix the workflow: The stable workflow calls an overridable creation hook.

Abstract Factory: build compatible families: Compare creating one product with supplying a coordinated product family.