Bridge Pattern

Following are the some explanations of bridge pattern:

  1. Bridge pattern separates the high level logic and low level logic to different classes.
  2. Create separate classes when there are multiple dimensions to a single class. For example, Shape class have one dimension of shape type such as Circle or Square. Shape can have Color as another dimension. If we see the combinations of subclasses Shape can are many. Such as RedSquare, BlueCircle, BlueSquare, RedCircle etc. To avoid this subclass explosion, we can put reference to Color in Shape which can be different implementations for Color.

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)