Skip to content

Instantly share code, notes, and snippets.

@simongarisch
Created October 16, 2019 23:24
Show Gist options
  • Save simongarisch/64fc56eea3caf97b005e878f25f90a8a to your computer and use it in GitHub Desktop.
Save simongarisch/64fc56eea3caf97b005e878f25f90a8a to your computer and use it in GitHub Desktop.
Python structural patterns - bridge
# The bridge pattern is about preferring composition over inheritance.
from abc import ABC, abstractmethod
class Color(ABC):
@abstractmethod
def fill_color(self):
pass
class Shape:
def __init__(self, color):
self.color = color
def color_shape(self):
print("{} filled with {}".format(
self.__class__.__name__,
self.color.fill_color()
))
class Rectangle(Shape):
def __init__(self, color):
super().__init__(color)
class Circle(Shape):
def __init__(self, color):
super().__init__(color)
class RedColor(Color):
def fill_color(self):
return "red color"
class BlueColor(Color):
def fill_color(self):
return "blue color"
if __name__ == "__main__":
s1 = Rectangle(RedColor())
s1.color_shape() # Rectangle filled with red color
s2 = Circle(BlueColor())
s2.color_shape() # Circle filled with blue color
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment