Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Bridge Pattern

Python Bridge Pattern

The Bridge pattern is a structural design pattern that separates the abstraction from its implementation so the two can vary independently. Simply put, it isseparating the multiple dimensions of variation of a thing so that each dimension can be extended independently.

A Real-life Analogy for the Bridge Pattern

Think about the relationship between a remote control and a TV:

The remote does not need to know which specific TV it is, and the TV does not need to know which remote it is; they are connected through a "bridge" and each can be upgraded independently.


Why Is the Bridge Pattern Needed?

Limitations of the Traditional Approach

Suppose we want to design a graphics drawing system that supports different shapes and colors:

Example

Traditional implementation - the class explosion problem

class

RedCircle:

   

def

draw

(

self

)

:

       

print

(

"Draw a red circle"

)

class

BlueCircle:

   

def

draw

(

self

)

:

       

print

(

"Draw a blue circle"

)

class

RedRectangle:

   

def

draw

(

self

)

:

       

print

(

"Draw a red rectangle"

)

class

BlueRectangle:

   

def

draw

(

self

)

:

       

print

(

"Draw a blue rectangle"

)

Every time a color or shape is added, a new class must be created

3 colors x 3 shapes = 9 classes!

Advantages of the Bridge Pattern

Example

Bridge Pattern Implementation

class

Color:

   

"""Color interface - implementation part"""

   

def

apply_color

(

self

)

:

       

pass

class

Shape:

   

"""Shape abstraction - abstraction part"""

   

def

init

(

self

,

color

)

:

       

self

.

color

=

color  

The key to bridging!

   

   

def

draw

(

self

)

:

       

pass

Only need: 3 colors + 3 shapes = 6 classes

Instead of: 3 x 3 = 9 classes


Core Structure of the Bridge Pattern

Let's understand the components of the Bridge pattern through a complete example:

Four Key Roles

  1. Abstraction (Abstraction): defines the abstract interface and holds a reference to the implementation
  2. Refined Abstraction (RefinedAbstraction): extends the abstract interface
  3. Implementor (Implementor): defines the implementation interface
  4. Concrete Implementor (ConcreteImplementor): concretely implements the interface

Complete Code Example: Graphics Drawing System

Step 1: Define the implementation interface (color)

Example

from

abc

import

ABC

,

abstractmethod

class

Color

(

ABC

)

:

   

"""Color interface - implementation part"""

   

@

abstractmethod

   

def

apply_color

(

self

)

:

       

pass

class

Red

(

Color

)

:

   

"""Concrete implementation - Red"""

   

def

apply_color

(

self

)

:

       

return

"Red"

class

Blue

(

Color

)

:

   

"""Concrete implementation - Blue"""

   

def

apply_color

(

self

)

:

       

return

"Blue"

class

Green

(

Color

)

:

   

"""Concrete implementation - Green"""

   

def

apply_color

(

self

)

:

       

return

"Green"

Step 2: Define the abstraction (shape)

Example

class

Shape

(

ABC

)

:

   

"""Shape abstraction - abstraction part"""

   

def

init

(

self

,

color: Color

)

:

       

self

.

color

=

color  

The key to bridging: hold a reference to the implementation

   

   

@

abstractmethod

   

def

draw

(

self

)

:

       

pass

class

Circle

(

Shape

)

:

   

"""Refined abstraction - Circle"""

   

def

draw

(

self

)

:

        color_name

=

self

.

color

.

apply_color

(

)

       

print

(

f

"Draw a {color_name} circle"

)

class

Rectangle

(

Shape

)

:

   

"""Refined abstraction - Rectangle"""

   

def

draw

(

self

)

:

        color_name

=

self

.

color

.

apply_color

(

)

       

print

(

f

"Draw a {color_name} rectangle"

)

class

Triangle

(

Shape

)

:

   

"""Refined abstraction - Triangle"""

   

def

draw

(

self

)

:

        color_name

=

self

.

color

.

apply_color

(

)

       

print

(

f

"Draw a {color_name} triangle"

)

Step 3: Use the Bridge pattern

Example

Client code

def

main

(

)

:

   

Create color implementations

    red

=

Red

(

)

    blue

=

Blue

(

)

    green

=

Green

(

)

   

   

Create shape abstractions and bridge the color implementations

    red_circle

=

Circle

(

red

)

    blue_rectangle

=

Rectangle

(

blue

)

    green_triangle

=

Triangle

(

green

)

   

   

Draw the shapes

   

print

(

"=== Shape Drawing Results ==="

)

    red_circle.

draw

(

)

       

Output: draw a red circle

    blue_rectangle.

draw

(

)

   

Output: draw a blue rectangle

    green_triangle.

draw

(

)

   

Output: draw a green triangle

   

   

Flexible combination: red rectangle

    red_rectangle

=

Rectangle

(

red

)

    red_rectangle.

draw

(

)

   

Output: draw a red rectangle

if

name

==

"main"

:

    main

(

)


Practical Application Scenarios

Scenario 1: Message Sending System

Example

from

abc

import

ABC

,

abstractmethod

Implementation Part: Message Sending Methods

class

MessageSender

(

ABC

)

:

   

@

abstractmethod

   

def

send

(

self

,

message

)

:

       

pass

class

EmailSender

(

MessageSender

)

:

   

def

send

(

self

,

message

)

:

       

return

f

"Send via email: {message}"

class

SMSSender

(

MessageSender

)

:

   

def

send

(

self

,

message

)

:

       

return

f

"Send via SMS: {message}"

class

WeChatSender

(

MessageSender

)

:

   

def

send

(

self

,

message

)

:

       

return

f

"Send via WeChat: {message}"

Abstraction Part: Message Types

class

Message

(

ABC

)

:

   

def

init

(

self

,

sender: MessageSender

)

:

       

self

.

sender

=

sender

   

   

@

abstractmethod

   

def

send

(

self

)

:

       

pass

class

UrgentMessage

(

Message

)

:

   

def

send

(

self

)

:

        message

=

"[Urgent] "

self

.

get_content

(

)

       

return

self

.

sender

.

send

(

message

)

   

   

def

get_content

(

self

)

:

       

return

"A system exception occurred, please handle it immediately!"

class

NormalMessage

(

Message

)

:

   

def

init

(

self

,

sender: MessageSender

,

content

)

:

       

super

(

)

.

init

(

sender

)

       

self

.

content

=

content

   

   

def

send

(

self

)

:

       

return

self

.

sender

.

send

(

self

.

content

)

Usage examples

def

message_example

(

)

:

    email_sender

=

EmailSender

(

)

    sms_sender

=

SMSSender

(

)

   

   

Urgent messages are sent via SMS

    urgent_sms

=

UrgentMessage

(

sms_sender

)

   

print

(

urgent_sms.

send

(

)

)

 

Send via SMS: [Urgent] A system exception occurred, please handle it immediately!

   

   

Normal messages are sent via email

    normal_email

=

NormalMessage

(

email_sender

,

"Monthly report has been generated"

)

   

print

(

normal_email.

send

(

)

)

 

Send via email: Monthly report has been generated

message_example

(

)

Scenario 2: Device Remote Control System

Example

Implementation Part: Devices

class

Device

(

ABC

)

:

   

@

abstractmethod

   

def

turn_on

(

self

)

:

       

pass

   

   

@

abstractmethod

   

def

turn_off

(

self

)

:

       

pass

   

   

@

abstractmethod

   

def

set_volume

(

self

,

volume

)

:

       

pass

class

TV

(

Device

)

:

   

def

turn_on

(

self

)

:

       

return

"TV is on"

   

   

def

turn_off

(

self

)

:

       

return

"TV is off"

   

   

def

set_volume

(

self

,

volume

)

:

       

return

f

"TV volume set to: {volume}"

class

Radio

(

Device

)

:

   

def

turn_on

(

self

)

:

       

return

"Radio is on"

   

   

def

turn_off

(

self

)

:

       

return

"Radio is off"

   

   

def

set_volume

(

self

,

volume

)

:

       

return

f

"Radio volume set to: {volume}"

Abstraction Part: Remote Control

class

RemoteControl:

   

def

init

(

self

,

device: Device

)

:

       

self

.

device

=

device

   

   

def

toggle_power

(

self

)

:

       

return

"Toggle power state"

   

   

def

volume_up

(

self

)

:

       

return

"Volume up"

   

   

def

volume_down

(

self

)

:

       

return

"Volume down"

class

AdvancedRemoteControl

(

RemoteControl

)

:

   

def

mute

(

self

)

:

       

return

"Mute mode"

   

   

def

set_channel

(

self

,

channel

)

:

       

return

f

"Switch to channel: {channel}"

Usage examples

def

remote_example

(

)

:

    tv

=

TV

(

)

    radio

=

Radio

(

)

   

    basic_remote

=

RemoteControl

(

tv

)

    advanced_remote

=

AdvancedRemoteControl

(

radio

)

   

   

print

(

basic_remote.

toggle_power

(

)

)

 

Toggle power state

   

print

(

advanced_remote.

mute

(

)

)

     

Mute mode

remote_example

(

)


Comparison of the Advantages of the Bridge Pattern

Feature Traditional Approach Bridge Pattern
Extensibility Poor, requires modifying existing code Good, can be extended independently
Number of Classes Many, prone to class explosion Few, linear growth
Maintainability Difficult, a small change affects the whole Easy, separation of concerns
Flexibility Fixed combination Dynamic combination at runtime

Best practices and notes

When to Use

✅ Situations suitable for the Bridge Pattern:

❌ Situations not suitable:

Common Mistakes and How to Avoid Them

Example

Incorrect Example: No Real Decoupling

class

BadShape:

   

def

init

(

self

,

color_type

)

:

       

if

color_type

==

"red"

:

           

self

.

color

=

Red

(

)

       

elif

color_type

==

"blue"

:

           

self

.

color

=

Blue

(

)

       

Still need to modify this class to add a new color

Correct Approach: Dependency Injection

class

GoodShape:

   

def

init

(

self

,

color: Color

)

:  

Depend on interfaces, not concrete implementations

       

self

.

color

=

color


Exercise tasks

Exercise 1: Extend the Shape System

Please add the following features to the shape system:

  1. Add a new color (yellow)
  2. Add a new shape (ellipse)
  3. Create a yellow ellipse and draw it

Exercise 2: Design a Payment System

Design a payment system with the following requirements:


Summary

The Bridge Pattern, byseparating abstraction and implementation, provides great flexibility. Its core idea is:

  1. Identify varying dimensions: find the multiple dimensions in the system that may vary independently
  2. Build a bridge: connect different dimensions through composition
  3. Independent extension: each dimension can evolve and change independently