...

Python设计模式-08-桥接模式

桥接模式是一种结构型设计模式,它将抽象部分和实现部分分离开来,使它们可以独立地变化。桥接模式通常包括以下几个角色:

  • 抽象部分(Abstraction):定义了抽象部分的接口,并持有一个实现部分的引用。
  • 扩展抽象部分(Refined Abstraction):扩展了抽象部分的接口,可以包含一些额外的行为。
  • 实现部分(Implementor):定义了实现部分的接口,可以是一个抽象类或接口。
  • 具体实现部分(Concrete Implementor):实现了实现部分的接口,并提供具体的实现。

下面是一个简单的 Python 示例,演示了如何使用桥接模式将抽象部分和实现部分分离开来:

class Abstraction:
    def __init__(self, implementor):
        self.implementor = implementor

    def operation(self):
        self.implementor.operation_implementation()

class RefinedAbstraction(Abstraction):
    def extended_operation(self):
        print('RefinedAbstraction: Extended operation.')
        self.implementor.operation_implementation()

class Implementor:
    def operation_implementation(self):
        pass

class ConcreteImplementorA(Implementor):
    def operation_implementation(self):
        print('ConcreteImplementorA: Operation implementation.')

class ConcreteImplementorB(Implementor):
    def operation_implementation(self):
        print('ConcreteImplementorB: Operation implementation.')

implementor_a = ConcreteImplementorA()
implementor_b = ConcreteImplementorB()

abstraction_a = Abstraction(implementor_a)
abstraction_a.operation()

abstraction_b = Abstraction(implementor_b)
abstraction_b.operation()

refined_abstraction_a = RefinedAbstraction(implementor_a)
refined_abstraction_a.operation()
refined_abstraction_a.extended_operation()

refined_abstraction_b = RefinedAbstraction(implementor_b)
refined_abstraction_b.operation()
refined_abstraction_b.extended_operation()

在上面的示例中,我们定义了一个抽象部分 Abstraction,它定义了抽象部分的接口,并持有一个实现部分的引用。然后,我们定义了一个扩展抽象部分 RefinedAbstraction,它扩展了抽象部分的接口,并可以包含一些额外的行为。接下来,我们定义了一个实现部分 Implementor,它定义了实现部分的接口。最后,我们定义了两个具体实现部分 ConcreteImplementorA 和 ConcreteImplementorB,它们实现了实现部分的接口,并提供具体的实现。

在使用桥接模式时,我们可以通过创建不同的抽象部分和实现部分的组合来实现不同的行为。在上面的示例中,我们创建了两个具体实现部分 ConcreteImplementorA 和 ConcreteImplementorB,并分别将它们与抽象部分 Abstraction 和 RefinedAbstraction 进行组合,从而实现了不同的行为。需要注意的是,桥接模式可以帮助我们将抽象部分和实现部分分离开来,使它们可以独立地变化,但也可能会导致代码的复杂性增加。

posted @ 2023-06-16 18:28  韩志超  阅读(91)  评论(0编辑  收藏  举报