Reading Time: 1 minutes
Bridge Design Pattern in Python
Write a Python program to implement Bridge Design Pattern.
# We have a Circle class having 3 attributes and 3 methods.
# Attributes are radius, coordinates on a 2-D plane.
# Methods are drawWithAPIOne(), drawWithAPITwo() and scale(). Of these, the drawing methods are implementation specific as we have two APIs to draw a circle, and it depends on the user which one to use.
# Our purpose here is to separate the Implementation Specific Abstraction and Implementaion Independent Abstraction into two different class hierarchies.
# We wish to keep the Circle class confined to defining its properties and implementation-independent scale() method AND have the draw functionality (which is implementation specific)
# delegated to a separate class hierarchy.
class DrawingAPIOne:
'''Implementation-specific abstraction'''
def drawCircle(self, x, y, radius):
print("API 1 is drawing a circle at ({}, {}) with radius {}".format(x, y, radius))
class DrawingAPITwo:
'''Implementation-specific abstraction'''
def drawCircle(self, x, y, radius):
print("API 2 is drawing a circle at ({}, {}) with radius {}".format(x, y, radius))
class Circle:
def __init__(self, x, y, radius, drawingAPI):
'''Implementation-independent abstraction; Initialize the necessary attributes'''
self._x = x
self._y = y
self._radius = radius
self._drawingAPI = drawingAPI
def draw(self):
'''Implementation-specific abstraction'''
self._drawingAPI.drawCircle(self._x, self._y, self._radius)
def scale(self, percent):
'''Implementation-independent abstraction'''
self._radius *= percent
# Instantiate a circle and pass to it an object of DrawingAPIOne in its 4rth argument
circle1 = Circle(0, 0, 2, DrawingAPIOne())
# Draw it using API One
circle1.draw()
# Instantiate another circle and pass to it an object of DrawingAPITwo in its 4rth argument
circle2 = Circle(1, 3, 3, DrawingAPITwo())
# Draw it using API Two
circle2.draw()







