4.9_bridge_结构型模式:桥模式

结构型模式
--- 桥模式 ---
内容:
    1. 将一个事物的两个维度分离,使其都可以独立地变化

角色:
    1. 抽象 (abstraction)
    2. 细化抽象 (Refined Abstraction)
    3. 实现者 (Implementor)
    4. 具体实现者 (Concrete Implementor)

适用场景:
    1. 当事物有两个维度上的表现,两个维度都可能扩展时

优点:
    1. 抽象和实现相分离
    2. 优秀的扩展能力
from abc import ABCMeta, abstractmethod


class Shape(metaclass=ABCMeta):
    """抽象 (abstraction)"""

    # 把 color 变为一个属性
    # 创建 shape 对象时,应传入一个 color 对象
    def __init__(self, color):
        self.color = color

    @abstractmethod
    def draw(self):
        pass


class Color(metaclass=ABCMeta):
    """实现者 (Implementor)"""

    @abstractmethod
    def paint(self, shape):
        pass


class Rectangle(Shape):
    name = '矩形'

    def draw(self):
        # color.paint 需要传入一个 shape 对象,把自己传进去
        # 矩形逻辑
        self.color.paint(self)


class Circle(Shape):
    name = '圆形'

    def draw(self):
        # 圆形逻辑
        self.color.paint(self)


class Line(Shape):
    name = '直线'

    def draw(self):
        # 直线逻辑
        self.color.paint(self)


class Red(Color):
    def paint(self, shape):
        # 写大块逻辑的部分为实现
        print(f'红色的 {shape.name}')


class Green(Color):
    def paint(self, shape):
        print(f'绿色的 {shape.name}')


class Blue(Color):
    def paint(self, shape):
        print(f'蓝色的 {shape.name}')


r = Line(Red())
r.draw()

r2 = Circle(Blue())
r2.draw()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值