Design Patterns - Bridge

Bridge(桥接) — 对象结构型模式

将一部分结构分离出去,使得对象和该部分结构能够自由的组合。听起来是不是很迷糊,举个例子,现在想要生成一个带颜色的图形,图形有长方形,圆形等等。那么我应该将颜色作为一个类分离出去,图形作为另一个类。

适用场景

  1. 你不希望在抽象部分和它部分实现(抽象部分:图形,部分实现:颜色)之间有一个固定的绑定关系。例如,这种情况可能是因为,在程序运行时实现部分应可以被选择或者切换。
  2. 抽象部分和部分实现都应该可以通过生成子类的方式加以扩充。这时 Bridge 模式使你可以对不同的抽象接口和实现部分进行组合。
  3. 对一个抽象的实现部分的修改应对客户不产生影响,即客户的代码不必重新编译。

UML图

在这里插入图片描述

效果

  1. 一个实现未必不变的绑定在一个接口上,抽象类的实现可以在运行时进行配置,一个对象甚至可以在运行时改变它的实现。
  2. 将 Abstraction 与 Implementor 分离有助于降低对实现部分编译时的依赖性,当改变一个实现类时,并不需要重新编译 Abstraction 类和它的客户程序。为了保证一个类库的不同版本之间的二进制兼容性,一定要有这个性质。
  3. 调高可扩充性:可以独立地对 Abstraction 和 Implementor 层次结构进行扩充。
  4. 实现细节对客户透明,可以对客户隐藏实现细节,例如共享 Implementor 对象相应的引用计数机制 (如果有的话)

示例

class Graphics(object):
    def __init__(self, color_implementor):
        self.color_implementor = color_implementor

    def draw(self):
        raise NotImplementedError

class Rectangle(Graphics):
    def draw(self):
        print("this is a {} rectangle".format(self.color_implementor.get_color()))

class Round(Graphics):
    def draw(self):
        print("this is a {} round".format(self.color_implementor.get_color()))

class ColorImplementor(object):
    def get_color(self):
        raise NotImplementedError

class GreenImplementor(ColorImplementor):
    def get_color(self):
        return "green"

class OrangeImplementor(ColorImplementor):
    def get_color(self):
        return "orange"

client

if __name__ == "__main__":
    rec1 = Rectangle(GreenImplementor())
    rec1.draw()
    rec2 = Rectangle(OrangeImplementor())
    rec2.draw()
    round1 = Round(GreenImplementor())
    round1.draw()
    round2 = Round(OrangeImplementor())
    round2.draw()

"""
output:
this is a green rectangle
this is a orange rectangle
this is a green round
this is a orange round
"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值