Abstract Factory Pattern in Python
Abstract Factory keeps compatible products together, such as widgets belonging to one visual theme.
What is Abstract Factory Pattern?
Abstract Factory keeps compatible products together, such as widgets belonging to one visual theme.
Create families of related objects without naming their concrete classes.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class DarkButton:
# Abstract Factory: create products that belong to one family.
def render(self): return "Dark button"
class DarkCheckbox:
def render(self): return "Dark checkbox"
class DarkThemeFactory:
# Produce a compatible family of UI objects.
def create_button(self): return DarkButton()
def create_checkbox(self): return DarkCheckbox()
factory = DarkThemeFactory()
print(factory.create_button().render())
print(factory.create_checkbox().render())
Expected output
Dark button
Dark checkbox
How it works
Each factory creates a matching button and checkbox, so client code never mixes product families.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.