桥接模式
桥接模式
桥接模式(Bridge Pattern)是一种结构型设计模式,它通过将抽象部分与它的实现部分分离,使它们都可以独立地变化。桥接模式通过组合而不是继承来实现这种分离,从而提高系统的可扩展性和灵活性。
桥接模式的特点
- 分离抽象和实现:将抽象部分与实现部分分离,使它们可以独立变化。
 - 提高系统的可扩展性:可以独立地扩展抽象部分和实现部分,而不会相互影响。
 - 更好的应对复杂性:适用于那些多维度变化的系统。
 
桥接模式的结构
- 抽象(Abstraction):定义抽象类的接口,包含一个对实现部分的引用。
 - 扩展抽象(Refined Abstraction):扩展抽象类,调用实现部分的接口。
 - 实现(Implementor):定义实现类的接口。
 - 具体实现(Concrete Implementor):具体实现实现类接口的方法。
 
桥接模式的Python实现
以下是桥接模式在Python中的一个实现示例:
1. 定义实现接口和具体实现类
from abc import ABC, abstractmethod
class Implementor(ABC):
    @abstractmethod
    def operation_impl(self) -> str:
        pass
class ConcreteImplementorA(Implementor):
    def operation_impl(self) -> str:
        return "ConcreteImplementorA: Here's the result on the platform A."
class ConcreteImplementorB(Implementor):
    def operation_impl(self) -> str:
        return "ConcreteImplementorB: Here's the result on the platform B."
2. 定义抽象和扩展抽象类
class Abstraction:
    def __init__(self, implementor: Implementor) -> None:
        self._implementor = implementor
    def operation(self) -> str:
        return f"Abstraction: Base operation with:\n{self._implementor.operation_impl()}"
class ExtendedAbstraction(Abstraction):
    def operation(self) -> str:
        return f"ExtendedAbstraction: Extended operation with:\n{self._implementor.operation_impl()}"
3. 客户端代码
def client_code(abstraction: Abstraction) -> None:
    print(abstraction.operation())
if __name__ == "__main__":
    implementor_a = ConcreteImplementorA()
    implementor_b = ConcreteImplementorB()
    abstraction = Abstraction(implementor_a)
    client_code(abstraction)
    print("\n")
    abstraction = ExtendedAbstraction(implementor_b)
    client_code(abstraction)
运行结果
Abstraction: Base operation with:
ConcreteImplementorA: Here's the result on the platform A.
ExtendedAbstraction: Extended operation with:
ConcreteImplementorB: Here's the result on the platform B.
说明
- 实现接口(Implementor):定义了实现部分的接口,即
operation_impl方法。 - 具体实现(ConcreteImplementorA 和 ConcreteImplementorB):实现了实现接口,提供具体的实现。
 - 抽象(Abstraction):定义了抽象部分的接口,包含一个对实现部分的引用,并实现了
operation方法。 - 扩展抽象(ExtendedAbstraction):扩展了抽象类,实现了具体的
operation方法。 - 客户端(Client):通过抽象接口与具体实现部分交互,而不直接依赖具体实现类。
 
通过桥接模式,可以在不改变抽象和实现类的情况下独立地扩展这两个部分,从而提高系统的灵活性和可扩展性。桥接模式适用于那些需要多维度变化的系统,例如需要支持多种平台、设备或多种格式的应用程序。