当前位置:首页>文章>设计模式>桥接模式详解 | Python桥接模式示例与应用解析

桥接模式详解 | Python桥接模式示例与应用解析

桥接模式详解

1️⃣ 概念

定义: 将抽象部分与它的具体实现部分分离,使他们都可以独立的变化;通过组合的方式建立两个类之间联系,而不是继承。
类型: 结构型

2️⃣ 适用场景

  • 抽象与具体实现之间增加更多的灵活性
  • 一个类存在两个(或多个)独立变化的维度,且这两个(或多个)维度都需要进行独立扩展
  • 不希望使用继承,或因为多层继承导致系统类的个数剧增

3️⃣ 优点

  • 分离抽象部分及其具体实现部分
  • 提高了系统的可扩展性
  • 符合开闭原则
  • 符合合成复用原则

4️⃣ 缺点

  • 增加了系统的理解与设计难度
  • 需要正确地识别出系统中两个独立变化的维度

5️⃣ 桥接模式 Coding

① 创建Account抽象基类

from abc import ABC, abstractmethod

class Account(ABC):
    @abstractmethod
    def open_account(self):
        pass

    @abstractmethod
    def show_account_type(self):
        pass

② 创建DepositAccount类继承Account类

class DepositAccount(Account):
    def open_account(self):
        print("打开定期账号")
        return DepositAccount()

    def show_account_type(self):
        print("这是一个定期账号")

③ 创建SavingAccount类继承Account类

class SavingAccount(Account):
    def open_account(self):
        print("打开活期账号")
        # ...
        return SavingAccount()

    def show_account_type(self):
        print("这是一个活期账号")

④ 创建抽象类Bank

from abc import ABC, abstractmethod

class Bank(ABC):
    def __init__(self, account: Account):
        self.account = account

    @abstractmethod
    def open_account(self):
        pass

⑤ 创建ABCBank类继承Bank类

class ABCBank(Bank):
    def __init__(self, account: Account):
        super().__init__(account)

    def open_account(self):
        print("打开中国农业银行账号")
        self.account.open_account()
        return self.account

⑥ 创建ICBCBank类继承Bank类

class ICBCBank(Bank):
    def __init__(self, account: Account):
        super().__init__(account)

    def open_account(self):
        print("打开中国工商银行账号")
        self.account.open_account()
        return self.account

⑦ UML类图

⑧ 创建测试文件

def test_bridge_pattern():
    # 工商银行开定期账户
    icbc_bank = ICBCBank(DepositAccount())
    icbc_account = icbc_bank.open_account()
    icbc_account.show_account_type()

    # 工商银行开活期账户
    icbc_bank2 = ICBCBank(SavingAccount())
    icbc_account2 = icbc_bank2.open_account()
    icbc_account2.show_account_type()

    # 农业银行开活期账户
    abc_bank = ABCBank(SavingAccount())
    abc_account = abc_bank.open_account()
    abc_account.show_account_type()

if __name__ == "__main__":
    test_bridge_pattern()

6️⃣ 桥接模式的实际应用

Python标准库 database API specification (PEP 249)

在Python中,数据库连接模块如sqlite3psycopg2等都遵循PEP 249规范,这是桥接模式的一个很好的实际应用例子。

您已阅读完《设计模式(共12篇)》专题的第 11 篇。请继续阅读该专题下面的文章:

设计模式

组合模式详解 | Python代码示例与应用场景

2025-9-9 9:40:47

设计模式

迭代器模式详解 - 行为型设计模式与应用

2025-9-11 14:08:42

搜索