python 结构型模式 桥模式

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

例子:画图有一些形状,支持长方形、直线和圆,,每个形状都画个不同的颜色,这个就是一个事物两个维度

第一个维度是形状
第二个我都是颜色

第一有两个维度是独立的,第二必须是都有的

from abc import ABCMeta, abstractmethod

#形状类,形状  组合方式
class Shape(metaclass=ABCMeta):
        #颜色作为形状的一个属性
        def __init__(self,color):
                self.color = color

        @abstractmethod
        def draw(self):
                pass

#color的paint方法,参数需要shape
class Color(metaclass=ABCMeta):
        @abstractmethod
        #给一个形状画颜色 
        def paint(self,shape):
                pass

#是一个长方形的对象
class Rectang(Shape):
        name = "长方形"
        def draw(self):
                #实际是通过颜色来进行实现的
                #长方形逻辑
                #color的paint方法,参数需要shape, 给paint函数传入self自己(形状:长方形)
                self.color.paint(self) 


class Circle(Shape):
        name = "圆形"
        def draw(self):
                #圆形逻辑
                self.color.paint(self)

class Red(Color):
        def paint(self,shape):
                print("红色的%s" % shape.name)


class Green(Color):
        def paint(self, shape):
        		#shape就是Circle或者Rectang对象
                print("绿色的%s" % shape.name)


shape = Rectang(Red())
shape.draw()
# 先把color对象传过来,以便draw调用
# (其实draw调用的时候,是调用color的paint方法,并把shape对象传给paint让它去调用shape的name)
shape2 = Circle(Green())
shape2.draw()

在这里插入图片描述
#Rectang是个形状,形状的构造函数是来源于父类的,color就要传一个颜色的对象进来
shape = Rectang(Red())
#调用darw()的时候
shape.draw()

角色

  • 抽象(Abstraction)
  • 细化抽象(RefinedAbstraction) 长方形 圆形 ,抽象的子类
  • 实现者(implementor) 实现这也有子类 红色,绿色
  • 具体实现者(Concretelmplementor)

应用场景

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

优点:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伟伟哦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值