Bridge Pattern
Following are the some explanations of bridge pattern:
- Bridge pattern separates the high level logic and low level logic to different classes.
- Create separate classes when there are multiple dimensions to a single class. For example,
Shapeclass have one dimension of shape type such asCircleorSquare.Shapecan haveColoras another dimension. If we see the combinations of subclassesShapecan are many. Such asRedSquare,BlueCircle,BlueSquare,RedCircleetc. To avoid this subclass explosion, we can put reference toColorinShapewhich can be different implementations forColor.
In programming example, if there is a Notepad class which enable write notes. Notes can be stored on file or cloud. To make Notepad working with both storage mechanism, either we create two subclasses and override methods which save the content, or we can provide an storage implementation which deals with saving the content. It solves the case where we require different type of Notepads. We can just extend Notepad class and add more respective methods.
class Notepad:
def __init__(self, storage_adapter):
self.content = "" # empty note
self.storage_adapter = storage_adapter
def write(self, lines):
self.content += lines
def save(self):
self.storage_adapter.save(self.content)
file_notepad = NotePad(FileStorage)
cloud_notepad = NotePad(GoogleStorage)