Thursday, March 12, 2009

Bridge Pattern


When I studied almost all of the Gang of Four Design Patterns back in 2005 or 2006, I knew only one language - C++.

Now I am proficient in multiple software languages and my viewpoint about Design Patterns has also matured..

So, here we go.

The Bridge Pattern implementation in Python.

Let me tell you in detail what is there in this example.

Here we have a top-level root class called Vehicle having two attributes - color and gear.

Color may be Red and White whereas the Gear may be Manual and Auto.

Now if we put all of these in a monolithic class hierarchy, as shown in the left diagram - there will be many classes.

So, to do it in a better fashion, we maintain two different inheritance hierarchies namely one for Color and another for Gear. And the Vehicle hierarchy is maintained separately.

So from the vehicle hierarchy, we pick up any color and any type of Gear we want from the Color and Gear inheritance hierarchies respectively as shown in the right-side diagram.

The result - there will be few classes to maintain.

This is exactly what is explained in the following section.

Look at the UML diagram on the left - that is the class hierarchy without using Bridge Pattern. Look at the number of classes - it's many classes.

Look at the class diagram at the right- look at how fewer classes can manage the same level of different classes if we use the Bridge Pattern


Here is the Python code for the bridge pattern whose class diagram is shown above.

from abc import ABC, abstractmethod

class Color(ABC):
def __init__(self):
pass

class Red(Color):
def __init__(self):
print("Its Color Red...")
class Black(Color):
def __init__(self):
print("It's Color Black...")


class Gear(ABC):
def __init__(self):
pass

class ManualGear(Gear):
def __init__(self):
print("It's a manual gear...")

class AutoGear(Gear):
def __init__(self):
print("It's a auto gear...")

class Vehicle:
def setColor(self, color):
self.color = color

def setGear(self, gear):
self.gear = gear

def display(self):
print("The ", type(car), " has color ", type(self.color), " and gear ", type(self.gear))

class Truck(Vehicle):
def __init__(self):
pass
class SmallCar(Vehicle):
def __init__(self):
pass
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
car = SmallCar()
redColor = Red()
autoGear = AutoGear()
car.setColor(redColor)
car.setGear(autoGear)
car.display()