Factory Method & Abstract Factory
You'll learn to
- -Use Factory Method to defer object creation to subclasses without the caller knowing the concrete type
- -Use Abstract Factory to produce families of related objects, and explain when it earns its extra layer
- -Recognize the lighter alternatives in Python: a simple factory function and a dictionary of classes
- -Answer the interview question: Factory Method, Abstract Factory, or neither?
Here is the problem both patterns solve. Somewhere in your code you write if kind == "pdf": doc = PDFDocument() elif kind == "word": doc = WordDocument(). It works, until the same if-chain appears in five places, and adding a Markdown document means finding and editing all five. The code that uses a document has been tied to every concrete kind of document. Factory patterns move the creation decision to one place and let the rest of the code depend only on the interface.
# Before: every place that creates a document knows every kind
def export(kind):
if kind == "pdf":
doc = PDFDocument()
elif kind == "word":
doc = WordDocument()
else:
raise ValueError(kind)
doc.save()
# The same if-chain appears in print(), preview(), email()...
# Adding "markdown" means editing every one of themAn Analogy: Franchise Kitchens and Furniture Showrooms
In a pizza franchise, headquarters defines what every branch does (take an order, bake, box) but each branch's kitchen decides which pizza it makes: the Chicago branch makes deep-dish, the New York branch thin crust. Customers just order. That is Factory Method: a template with one step, creating the product, left to the subclass. Now picture a furniture showroom with a Modern and a Victorian collection. Whichever collection you pick, the chair, the sofa and the table all match each other, and you can never end up with a Victorian chair at a Modern table. That is Abstract Factory.
- -The franchise's standard routine is the base class method (export) that calls the factory method.
- -Each branch deciding its own pizza is a subclass overriding create_document().
- -A showroom collection is a concrete factory (DarkThemeFactory), and the matching chair, sofa and table are the family of products it creates.
Factory Method: One Product, Deferred to Subclasses
Factory Method defines a method for creating an object, but lets subclasses decide which concrete class to instantiate. A DocumentCreator base class might declare create_document(), with PDFCreator and WordCreator subclasses each returning their own concrete Document type - callers work against DocumentCreator and never need an if/elif on document type.
class DocumentCreator(ABC):
@abstractmethod
def create_document(self) -> Document: ...
def export(self) -> None: # uses the factory method, doesn't know the concrete type
doc = self.create_document()
doc.save()
class PDFCreator(DocumentCreator):
def create_document(self) -> Document:
return PDFDocument()
class WordCreator(DocumentCreator):
def create_document(self) -> Document:
return WordDocument()Abstract Factory: Families That Must Stay Consistent
Abstract Factory earns its extra layer when you are creating several related objects that must be mutually compatible - a UI toolkit that needs a Button, Checkbox, and ScrollBar that are all either consistently "dark theme" or consistently "light theme," never a mismatched mix. A single factory interface exposes create_button(), create_checkbox(), and create_scrollbar(), and each concrete factory (DarkThemeFactory, LightThemeFactory) guarantees every product it returns belongs to the same family.
class UIFactory(ABC):
@abstractmethod
def create_button(self) -> Button: ...
@abstractmethod
def create_checkbox(self) -> Checkbox: ...
class DarkThemeFactory(UIFactory):
def create_button(self) -> Button: return DarkButton()
def create_checkbox(self) -> Checkbox: return DarkCheckbox()
class LightThemeFactory(UIFactory):
def create_button(self) -> Button: return LightButton()
def create_checkbox(self) -> Checkbox: return LightCheckbox()
def render_form(factory: UIFactory):
# can never accidentally mix a DarkButton with a LightCheckbox
button, checkbox = factory.create_button(), factory.create_checkbox()Lighter Options in Python
Be ready to say that the full patterns are often more machinery than Python needs. Classes are ordinary values in Python, so a dictionary does the same job as a factory with an if-chain:
CREATORS = {"pdf": PDFDocument, "word": WordDocument}
def create_document(kind):
return CREATORS[kind]() # one place to add a new kindFactory Method proper earns its place when a framework wants subclasses to supply the product while the base class runs the surrounding routine, as export() does above. Abstract Factory earns it when several products must stay consistent as a set.
The interview tell for "do I need Abstract Factory, or is Factory Method enough": ask whether the products need to be consistent as a set. If there is only ever one product type being created, Abstract Factory's extra layer is unjustified complexity.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.
Discussion0
Join the Discussion
Sign in to leave comments, reply to others, or like insights.
No comments yet. Be the first to start the thread!