zoukankan      html  css  js  c++  java
  • 结构型模式(二) 桥接模式

    桥接模式(Bridge Pattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。也叫做桥梁模式。

    扩展性强:抽象角色和实现角色可以非常灵活地扩展。
    不适用继承或者原继承关系中抽象类可能频繁变动的情况,可以将原类进行拆分,拆成实现化角色和抽象化角色。
    将两个角色之间的继承关系改为聚合关系,将它们之间的强关联改换成为弱关联。

    # ConcreteImplementor 1/2
    class DrawingAPI1(object):
        def draw_circle(self, x, y, radius):
            print('API1.circle at {}:{} radius {}'.format(x, y, radius))
     
     
    # ConcreteImplementor 2/2
    class DrawingAPI2(object):
        def draw_circle(self, x, y, radius):
            print('API2.circle at {}:{} radius {}'.format(x, y, radius))
     
     
    # Refined Abstraction
    class CircleShape(object):
        def __init__(self, x, y, radius, drawing_api):
            self._x = x
            self._y = y
            self._radius = radius
            self._drawing_api = drawing_api
     
        # low-level i.e. Implementation specific
        def draw(self):
            self._drawing_api.draw_circle(self._x, self._y, self._radius)
     
        # high-level i.e. Abstraction specific
        def scale(self, pct):
            self._radius *= pct
     
     
    def main():
        shapes = (
            CircleShape(1, 2, 3, DrawingAPI1()),
            CircleShape(5, 7, 11, DrawingAPI2())
        )
     
        for shape in shapes:
            shape.scale(2.5)
            shape.draw()
     
     
    if __name__ == '__main__':
        main()

    结果:

    API1.circle at 1:2 radius 7.5
    API2.circle at 5:7 radius 27.5

  • 相关阅读:
    [leetcode]N-Queens II @ Python
    [leetcode]N-Queens @ Python
    [leetcode]Symmetric Tree @ Python
    [leetcode]Same Tree @ Python
    [leetcode]Validate Binary Search Tree @ Python
    [leetcode]Recover Binary Search Tree @ Python
    关于Kubernetes Master高可用的一些策略
    hue 登录访问不了HDFS webhdfs_url 调整
    java项目代码上线
    nginx实现最简单的直播
  • 原文地址:https://www.cnblogs.com/dxnui119/p/12035955.html
Copyright © 2011-2022 走看看