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,
Shape
class have one dimension of shape type such asCircle
orSquare
.Shape
can haveColor
as another dimension. If we see the combinations of subclassesShape
can are many. Such asRedSquare
,BlueCircle
,BlueSquare
,RedCircle
etc. To avoid this subclass explosion, we can put reference toColor
inShape
which 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 Notepad
s. 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)