Skip to content

Bridge

The Bridge is a pattern that allows you to separate abstractions that are related to each other by inheritance. Suppose we implement a simple shop that sells drinks - coffee or tea. Each of these drinks can be purchased by inheriting the corresponding object representing the purchase. In this case, the implementation is closely related to the abstraction (e.g. the Coffee class together with the CoffeePurchase class, which could represent a purchase), which implies numerous changes in many classes in case of a change of concept. A better idea is to separate the abstraction from the implementation and group the existing elements into separate class hierarchies.

The implementation of the above-described case without the use of Bridge could look like this:

no_bridge

Using the bridge, we can divide these objects into two groups:

  • Coffee, Tea with the separation of the common interface Drink
  • CoffeePurchase, TeaPurchase, along with the separation of a common interface for this abstraction - DrinkPurchase

Thanks to this (single) link (the so-called bridge), interfaces are between these abstraction hierarchies Drink i DrinkPurchase.

bridge

An implementation with Bridge could look like this:

class Drink:
    def get_volume(self):
        pass

    def is_addictive(self):
        pass

    def get_number_of_sugar_lumps(self):
        pass

    def get_taste(self):
        pass
class Coffee(Drink):
    def get_volume(self):
        return "150ml"

    def is_addictive(self):
        return True

    def get_number_of_sugar_lumps(self):
        return 0

    def get_taste(self):
        return "bitter"
class Tea(Drink):
    def get_volume(self):
        return "250ml"

    def is_addictive(self):
        return False

    def get_number_of_sugar_lumps(self):
        return 2

    def get_taste(self):
        return "sweet"
class DrinkPurchase:
    def buy(self, cost):
        pass
class CoffeePurchase(DrinkPurchase):
    def buy(self, cost):
        print(f"Buying a coffee for {cost}")
        return Coffee()
class TeaPurchase(DrinkPurchase):
    def buy(self, cost):
        print(f"Buying a tea for {cost}")
        return Tea()