设计模式-结构型-桥模式

桥模式

概述

  • 将一个事物的两个维度分离,使其可以独立的变化

对象

  • 抽象(Abstraction)
  • 细化抽象(RefindAbstraction)
  • 实现者(Implementor)
  • 具体实现者(ConcreteImplementor)

适用场景

  • 当事物有两个维度上的表现, 并且在每个维度都有可能扩展时

例子

# 假设我们要进行不同颜色的形状绘制时,我们通常的  
# 做法是通过继承的方式分别对不同形状与颜色组合实  
# 现类的方式,例如红色矩形,红色矩形继承矩形,矩
# 形继承形状,桥模式将形状与颜色进行解耦,使用组
# 合方式在两个维度进行扩展

from abc import ABCMeta, abstractmethod

class Shape(metaclass=ABCMeta):
    def __init__(self, color):
        self.color = color
    
    @abstractmethod
    def draw(self):
        pass

class Color(metaclass=ABCMeta):

    @abstractmethod
    def paint(self, shape):
        pass

class Rectangle(Shape):
    name = "矩形"
    def draw(self):
        self.color.paint(self)

class Circular(Shape):
    name = "圆"
    def draw(self):
        self.color.paint(self)

class Red(Color):
    name = "红色"
    def paint(self, shape):
        print(f"{Red.name}的{shape.name}")

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

rectangle = Rectangle(Red())
rectangle.draw()

优点

  • 抽象与实现相分离
  • 优秀的扩展能力
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值