certain-design-patterns/bridge.py

38 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

from abc import ABC, abstractmethod
class Color(ABC): # реализация (задает общий интерфейс для всех реализаций)
@abstractmethod
def fillColor(self): pass
class BlackColor(Color): # конкретная реализация
def fillColor(self): print("Filling in black color")
class GreenColor(Color): # конкретная реализация
def fillColor(self): print("Filling in green color")
class RedColor(Color): # конкретная реализация
def fillColor(self): print("Filling in red color")
class Shape(ABC): # абстракция
def __init__(self, color): self.color = color # собственно, мост
@abstractmethod
def draw(self): pass
class Rectangle(Shape): # клиент (бизнес логика)
def __init__(self, color): super().__init__(color)
def draw(self):
print("Drawing rectangle")
self.color.fillColor()
class Triangle(Shape): # клиент (бизнес логика)
def __init__(self, color): super().__init__(color)
def draw(self):
print("Drawing triangle")
self.color.fillColor()
# Пример использования
black, green, red = BlackColor(), GreenColor(), RedColor() # МОСТ ПОЗВОЛИЛ ОТДЕЛЬНО СОЗДАТЬ РЕАЛИЗАЦИИ
rectangle, triangle = Rectangle(black), Triangle(green)
rectangle.draw()
triangle.draw()