CreationalPythonverifiedVerified

Abstract Factory Pattern in Python

Provides an interface for creating families of related objects without specifying their concrete classes.

How to Implement the Abstract Factory Pattern in Python

1Step 1: Define the product interfaces

from abc import ABC, abstractmethod


class Button(ABC):
    @abstractmethod
    def render(self) -> str: ...


class TextInput(ABC):
    @abstractmethod
    def render(self) -> str: ...

2Step 2: Define the abstract factory interface

class UIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button: ...

    @abstractmethod
    def create_text_input(self) -> TextInput: ...

3Step 3: Implement concrete product families

class DarkButton(Button):
    def render(self) -> str:
        return "<button class='dark-btn'>Click</button>"


class DarkTextInput(TextInput):
    def render(self) -> str:
        return "<input class='dark-input' />"


class DarkThemeFactory(UIFactory):
    def create_button(self) -> Button:
        return DarkButton()

    def create_text_input(self) -> TextInput:
        return DarkTextInput()


class LightButton(Button):
    def render(self) -> str:
        return "<button class='light-btn'>Click</button>"


class LightTextInput(TextInput):
    def render(self) -> str:
        return "<input class='light-input' />"


class LightThemeFactory(UIFactory):
    def create_button(self) -> Button:
        return LightButton()

    def create_text_input(self) -> TextInput:
        return LightTextInput()

4Step 4: Build forms using any factory

def build_form(factory: UIFactory) -> str:
    button = factory.create_button()
    text_input = factory.create_text_input()
    return f"Form: {text_input.render()} {button.render()}"


print(build_form(DarkThemeFactory()))
print(build_form(LightThemeFactory()))

Abstract Factory Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Abstract Factory Pattern in the Real World

Imagine furnishing a room from IKEA versus a luxury boutique. Each store (factory) produces a complete set of furniture — chairs, tables, sofas — that share a consistent style. You pick the store, and every piece you get matches. You never mix a rustic IKEA chair with a baroque boutique table.