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.
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
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.