Bridge

Bridge

  • The Bridge design pattern allows you to separate the abstraction from the implementation
  • It is a structural design pattern.
  • This is a design mechanism that encapsulates an implementation class inside of an interface class.
  • The bridge pattern allows the Abstraction and the Implementation to be developed independently and the client code can access only the Abstraction part without being concerned about the Implementation part.
  • It increases the loose coupling between class abstraction and it’s implementation.
  • It uses composition over the inheritance.

Example of bridge pattern

  • Let's consider the simple example of shapes Circle and Square.
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def display(self):
        pass

class Square(Shape):
    def display(self):
        print("square")

class Circle(Shape):
    def display(self):
        print("circle")

If we want to create colored Circle and Square then we need onemore class Color. If we use inheritance then we end up creating multiple subclasses. By using composition we can reduce the number of classes and improve the code maintainability.

Let's write the color classes

from abc import ABC, abstractmethod

class Color(ABC):
    @abstractmethod
    def get_color(self):
        pass

class Red(Color):
    def get_color(self):
        print("Color Red")

class Blue(Color):
    def get_color(self):
        print("Color Blue")

Now, let update our abstract class Shape to accept the color as argument and abstract it.

class Shape(ABC):
    def __init__(self, color: Color):
        self.color = color

    def get_color(self):
        self.color.get_color()

    @abstractmethod
    def display(self):
        pass

As, we exposed methods get_color and display to the client on class Shape. so, client will only use these methods. Let's see the client implementation

color = Blue()
blue_square = Square(color)

blue_square.display()
blue_square.get_color()

# output
# square
# Color Blue

You can find full code at github

References: