Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Composite Method - Python Design Patterns
Next article icon

Bridge Method - Python Design Patterns

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.
The bridge Method is always considered as one of the best methods to organize the class hierarchy.

Bridge-Method
Bridge Method

Elements of Bridge Design Pattern

  • Abstraction: It is the core of the Bridge Design Pattern and it provides the reference to the implementer.
  • Refined Abstraction: It extends the abstraction to a new level where it takes the finer details one level above and hides the finer element from the implementers.
  • Implementer: It defines the interface for implementation classes. This interface does not need to correspond directly to the abstraction interface and can be very different.
  • Concrete Implementation: Through the concrete implementation, it implements the above implementer.

Problem without using Bridge Method

Consider the following class Cuboid which has three attributes named length, breadth, and height and three methods named ProducewithAPI1(), ProduceWithAPI2(), and expand(). 
Out of these, producing methods are implementation-specific as we have two production APIs, and one method i.e., expand() method is implementation-independent. 

Till now we have only two implementation-specific methods and one implementation-independent method but when the quantity will rise (of course in a large-scale project) things will become messy for the developers to handle.
 

Problem-Bridge-Method
Problem-Bridge-Method


Note: Following code is written without using the Bridge method.

Python3
""" Code without using the bridge method     We have a class with three attributes     named as length, breadth, and height and     three methods named as ProduceWithAPI1(),     ProduceWithAPI2(), and expand(). Out of these     producing methods are implementation-specific     as we have two production APIs"""  class Cuboid:      class ProducingAPI1:          """Implementation Specific Implementation"""          def produceCuboid(self, length, breadth, height):              print(f'API1 is producing Cuboid with length = {length}, '                   f' Breadth = {breadth} and Height = {height}')      class ProducingAPI2:         """Implementation Specific Implementation"""          def produceCuboid(self, length, breadth, height):             print(f'API2 is producing Cuboid with length = {length}, '                   f' Breadth = {breadth} and Height = {height}')       def __init__(self, length, breadth, height):          """Initialize the necessary attributes"""          self._length = length         self._breadth = breadth         self._height = height      def produceWithAPI1(self):          """Implementation specific Abstraction"""          objectAPIone = self.ProducingAPI1()         objectAPIone.produceCuboid(self._length, self._breadth, self._height)      def producewithAPI2(self):          """Implementation specific Abstraction"""          objectAPItwo = self.ProducingAPI2()         objectAPItwo.produceCuboid(self._length, self._breadth, self._height)      def expand(self, times):          """Implementation independent Abstraction"""          self._length = self._length * times         self._breadth = self._breadth * times         self._height = self._height * times  # Instantiate a Cuboid cuboid1 = Cuboid(1, 2, 3)  # Draw it using APIone cuboid1.produceWithAPI1()  # Instantiate another Cuboid cuboid2 = Cuboid(19, 20, 21)  # Draw it using APItwo cuboid2.producewithAPI2() 

Solution using Bridge method

Now let's look at the solution for the above problem. The bridge Method is one of the best solutions for such kinds of problems. Our main purpose is to separate the codes of implementation-specific abstractions and implementation-independent abstractions.

Solution-Bridge-method
Solution-Bridge-Method


Note: Following Code is written using Bridge Method

Python3
"""Code implemented with Bridge Method.    We have a Cuboid class having three attributes    named as length, breadth, and height and three    methods named as produceWithAPIOne(), produceWithAPItwo(),    and expand(). Our purpose is to separate out implementation    specific abstraction from implementation-independent    abstraction"""  class ProducingAPI1:      """Implementation specific Abstraction"""      def produceCuboid(self, length, breadth, height):          print(f'API1 is producing Cuboid with length = {length}, '               f' Breadth = {breadth} and Height = {height}')  class ProducingAPI2:      """Implementation specific Abstraction"""      def produceCuboid(self, length, breadth, height):          print(f'API2 is producing Cuboid with length = {length}, '               f' Breadth = {breadth} and Height = {height}')  class Cuboid:      def __init__(self, length, breadth, height, producingAPI):          """Initialize the necessary attributes            Implementation independent Abstraction"""          self._length = length         self._breadth = breadth         self._height = height          self._producingAPI = producingAPI      def produce(self):          """Implementation specific Abstraction"""          self._producingAPI.produceCuboid(self._length, self._breadth, self._height)      def expand(self, times):          """Implementation independent Abstraction"""          self._length = self._length * times         self._breadth = self._breadth * times         self._height = self._height * times   """Instantiate a cuboid and pass to it an    object of ProducingAPIone"""  cuboid1 = Cuboid(1, 2, 3, ProducingAPI1()) cuboid1.produce()  cuboid2 = Cuboid(19, 19, 19, ProducingAPI2()) cuboid2.produce() 

UML Diagram of Bridge Method

Following is the UML diagram for Bridge Method
 

UML-Diagram-bridge-Method
UML -diagram-Bridge-Method

Advantages

  • Single Responsibility Principle: The bridge method clearly follows the Single Responsibility principle as it decouples an abstraction from its implementation so that the two can vary independently.
  • Open/Closed Principle: It does not violate the Open/Closed principle because at any time we can introduce the new abstractions and implementations independently from each other
  • Platform independent feature: Bridge Method can be easily used for implementing the platform-independent features.

Disadvantages

  • Complexity: Our code might become complex after applying the Bridge method because we are intruding on new abstraction classes and interfaces.
  • Double Indirection: The bridge method might have a slight negative impact on the performance because the abstraction needs to pass messages along with the implementation for the operation to get executed.
  • Interfaces with only a single implementation: If we have only limited interfaces, then it doesn't sweat a breath but if you have an exploded set of interfaces with minimal or only one implementation it becomes hard to manage

Applicability

  • Run-time Binding: Generally Bridge method is used to provide the run-time binding of the implementation, here run-time binding refers to what we can call a method at run-time instead of compile-time.
  • Mapping classes: The bridge method is used to map the orthogonal class hierarchies
  • UI Environment: A real-life application of the Bridge method is used in the definition of shapes in a UI Environment


Further read: Bridge Method in Java
 


Next Article
Composite Method - Python Design Patterns
author
chaudhary_19
Improve
Article Tags :
  • Python
  • Design Pattern
  • System Design
  • python-design-pattern
Practice Tags :
  • python

Similar Reads

  • Python Design Patterns Tutorial
    Design patterns in Python are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best pra
    8 min read
  • Creational Software Design Patterns in Python

    • Factory Method - Python Design Patterns
      Factory Method is a Creational Design Pattern that allows an interface or a class to create an object, but lets subclasses decide which class or object to instantiate. Using the Factory method, we have the best ways to create an object. Here, objects are created without exposing the logic to the cli
      4 min read
    • Abstract Factory Method - Python Design Patterns
      Abstract Factory Method is a Creational Design pattern that allows you to produce the families of related objects without specifying their concrete classes. Using the abstract factory method, we have the easiest ways to produce a similar type of many objects. It provides a way to encapsulate a group
      4 min read
    • Builder Method - Python Design Patterns
      Builder Method is a Creation Design Pattern which aims to "Separate the construction of a complex object from its representation so that the same construction process can create different representations." It allows you to construct complex objects step by step. Here using the same construction code
      5 min read
    • Prototype Method Design Pattern in Python
      The Prototype Method Design Pattern in Python enables the creation of new objects by cloning existing ones, promoting efficient object creation and reducing overhead. This pattern is particularly useful when the cost of creating a new object is high and when an object's initial state or configuratio
      6 min read
    • Singleton Method - Python Design Patterns
      Prerequisite: Singleton Design pattern | Introduction What is Singleton Method in PythonSingleton Method is a type of Creational Design pattern and is one of the simplest design patterns available to us. It is a way to provide one and only one object of a particular type. It involves only one class
      5 min read
    • Structural Software Design Patterns in Python

      • Adapter Method - Python Design Patterns
        Adapter method is a Structural Design Pattern which helps us in making the incompatible objects adaptable to each other. The Adapter method is one of the easiest methods to understand because we have a lot of real-life examples that show the analogy with it. The main purpose of this method is to cre
        4 min read
      • Bridge Method - Python Design Patterns
        The bridge method is a Structural Design Pattern that allows us to separate the Implementation Specific Abstractions and Implementation Independent Abstractions from each other and can be developed considering as single entities.The bridge Method is always considered as one of the best methods to or
        5 min read
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences