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 = nameclass CarFactory:@classmethoddef create_car(cls, name):return Car(name)car = CarFactory.create_car("BMW")car.drive() # Output: Driving BMWfrom abc import ABC, abstractmethodclass Button(ABC):@abstractmethoddef click(self):passclass WindowsButton(Button):def click(self):print("Windows button clicked")class MacButton(Button):def click(self):print("Mac button clicked")class GUIFactory(ABC):@abstractmethoddef create_button(self):passclass 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 clickedSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
