Before applying Abstract Factory, the Application class directly creates platform-specific buttons, causing tight coupling and hard-to-maintain code. After applying Abstract Factory, the Application depends on an abstract factory interface to create buttons, allowing easy extension to new platforms by adding new factories without changing Application code.
### Before: Without Abstract Factory
class WindowsButton:
def click(self):
print("Windows button clicked")
class MacOSButton:
def click(self):
print("MacOS button clicked")
class Application:
def __init__(self, os_type):
if os_type == "Windows":
self.button = WindowsButton()
else:
self.button = MacOSButton()
def click_button(self):
self.button.click()
app = Application("Windows")
app.click_button()
### After: With Abstract Factory
from abc import ABC, abstractmethod
class Button(ABC):
@abstractmethod
def click(self):
pass
class WindowsButton(Button):
def click(self):
print("Windows button clicked")
class MacOSButton(Button):
def click(self):
print("MacOS button clicked")
class GUIFactory(ABC):
@abstractmethod
def create_button(self) -> Button:
pass
class WindowsFactory(GUIFactory):
def create_button(self) -> Button:
return WindowsButton()
class MacOSFactory(GUIFactory):
def create_button(self) -> Button:
return MacOSButton()
class Application:
def __init__(self, factory: GUIFactory):
self.button = factory.create_button()
def click_button(self):
self.button.click()
factory = WindowsFactory()
app = Application(factory)
app.click_button()