Sobes.tech
Junior — Middle

Have you applied the 'Abstract Factory' pattern in your projects?

sobes.tech AI

Answer from AI

The "Abstract Factory" pattern is used to create families of related objects without specifying their concrete classes. In my Python projects, I applied this pattern when I needed to create objects of different families, for example, for different platforms or themes, while maintaining a unified interface.

Example of implementing an abstract factory in Python:

from abc import ABC, abstractmethod

class Button(ABC):
    @abstractmethod
    def render(self):
        pass

class WinButton(Button):
    def render(self):
        return "Rendering Windows button"

class MacButton(Button):
    def render(self):
        return "Rendering MacOS button"

class GUIFactory(ABC):
    @abstractmethod
    def create_button(self) -> Button:
        pass

class WinFactory(GUIFactory):
    def create_button(self) -> Button:
        return WinButton()

class MacFactory(GUIFactory):
    def create_button(self) -> Button:
        return MacButton()

# Usage

def client_code(factory: GUIFactory):
    button = factory.create_button()
    print(button.render())

client_code(WinFactory())  # Rendering Windows button
client_code(MacFactory())  # Rendering MacOS button

This approach simplifies the extension and maintenance of the code when adding a new platform or product family.