• 7.Python_结构型模式_桥模式


    1.定义

    12
    定义将抽象部分与实现部分解耦,使它们都可以独立的变化
    角色抽象(Abstraction):Shape
    细化抽象(RefnedAbstraction) :长方形,圆形
    实现者(implementor):Color
    具体实现者(ConcreImplementor):红色,蓝色
    优点1.抽象和实现的分离.2,优秀的扩展能力, 3,实现细节对客户透明。
    缺点桥接模式的引入会增加系统的理解与设计难度,由于聚合关联关系建立在抽象层,要求开发者针对抽象进行设计与编程
    应用场景1,如果一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性,避免在两个层次之间建立静态的继承联系,通过桥接模式可以使它们在抽象层建立一个关联关系
    2,对于那些不希望使用继承或因为多层次继承导致系统类的个数急剧增加的系统,桥接模式尤为适用
    3,一个类存在两个独立变化的维度,且这两个维度都需要进行扩展

    2.示例

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    from abc import ABCMeta, abstractmethod
    
    
    # 抽象者
    class Shape(metaclass=ABCMeta):
        # 聚合关联关系:与颜色进行关联
        def __init__(self, color):
            self.color = color
    
        @abstractmethod
        def draw(self):
            pass
    
    
    # 细化抽象
    class Rectangle(Shape):
        name = "长方形"
    
        def draw(self):
            self.color.paint(self)
    
    
    class Circle(Shape):
        name = "圆形"
    
        def draw(self):
            self.color.paint(self)
    
    
    # 实现者
    class Color(metaclass=ABCMeta):
        @abstractmethod
        def paint(self, shape):
            pass
    
    
    # 具体实现者
    class Red(Color):
        def paint(self, shape):
            print("红色的%s" % shape.name)
    
    
    class Black(Color):
        def paint(self, shape):
            print("黑色的%s" % shape.name)
    
    
    if __name__ == '__main__':
        rect = Rectangle(Red())
        rect.draw()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
  • 相关阅读:
    通过工作组在DAO中展开更有效的治理
    Java反射机制
    K3wise 常用表及视图
    文件的编译与链接
    Unigui可以使用WebSocket进行客户端之间的实时互相发消息
    [oeasy]python0019_ 打包和解包_struct_pack_unpack
    Redis 高可用之持久化
    java EE 多线程(一)
    【Leetcode】单链表oj(下),难度提升,快来做做.
    C++学习之路-C++11的新特性
  • 原文地址:https://blog.csdn.net/weixin_44689630/article/details/126451412