Fundamentals 6 min read

Factory Pattern and Abstract Factory Pattern in Python

This article introduces factory and abstract factory patterns in Python, including their concepts, implementations, and practical examples.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Factory Pattern and Abstract Factory Pattern in Python

This article introduces factory and abstract factory patterns in Python, including their concepts, implementations, and practical examples.

The factory pattern is a creational design pattern that encapsulates object creation logic, while the abstract factory pattern creates families of related objects.

In Python, the factory pattern can be implemented using class methods, as shown in the example where a CarFactory class creates Car objects.

The abstract factory pattern uses abstract base classes to define interfaces for creating related products, demonstrated with a GUIFactory interface and concrete implementations for Windows and Mac buttons.

The article also lists 10 practical scenarios where these patterns are applied, such as creating database connections, logging systems, and task schedulers.

The main difference between the two patterns is that the factory pattern focuses on single object creation, while the abstract factory pattern handles families of related objects.

Overall, these patterns provide flexibility and decoupling in object creation, making systems more extensible and maintainable.

class Car:

def __init__(self, name):

self.name = name

class CarFactory:

@classmethod

def create_car(cls, name):

return Car(name)

car = CarFactory.create_car("BMW")

car.drive() # Output: Driving BMW

from abc import ABC, abstractmethod

class Button(ABC):

@abstractmethod

def click(self):

pass

class WindowsButton(Button):

def click(self):

print("Windows button clicked")

class MacButton(Button):

def click(self):

print("Mac button clicked")

class GUIFactory(ABC):

@abstractmethod

def create_button(self):

pass

class WindowsFactory(GUIFactory):

def create_button(self):

return WindowsButton()

class MacFactory(GUIFactory):

def create_button(self):

return MacButton()

factory = WindowsFactory()

button = factory.create_button()

button.click() # Output: Windows button clicked

design patternsPythonsoftware developmentOOPFactory PatternAbstract Factory Pattern
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.