设计模式(Python语言)----桥模式(python编程实战:运用设计模式)

网友投稿 295 2022-08-23


设计模式(Python语言)----桥模式(python编程实战:运用设计模式)

更多信息请参考 【设计模式】

桥模式内容

将一个事务的两个维度分离,使其都可以独立地变化

桥模式中的角色

抽象(Abstraction)细化抽象(Refined Abstraction)实现者(Implementor)具体实现者(concrete Implementor)

桥模式的使用场景

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

桥模式的优点

抽象和实现相分离优秀的扩展能力

桥模式实例

(1)未使用桥模式时,类设计如下,即形状和颜色两个维度都变化时,类的数量是很多的

class Shape: passclass Line(Shape): passclass Rectangle(Shape): passclass Circle(Shape): passclass RedLine(Line): passclass GreenLine(Line): passclass BlueLine(Line): passclass RedRectangle(Rectangle): passclass GreeRectangle(Rectangle): passclass BlueRectangel(Rectangle): passclass RedCircle(Circle): passclass GreenCircle(Circle): passclass BlueCircle(Circle): pass

(2)使用桥模式时,类代码如下:

from abc import ABCMeta,abstractmethodclass Shape(metaclass=ABCMeta): def __init__(self,color): self.color=color @abstractmethod def draw(self): passclass Color(metaclass=ABCMeta): @abstractmethod def paint(self,shape): passclass 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}")class Rectangle(Shape): name="长方形" def draw(self): 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)if __name__=="__main__": shap1=Rectangle(Red()) shap1.draw() shap2=Circle(Blue()) shap2.draw() shap3=Line(Green()) shap3.draw()

执行结果如下:

红色的长方形蓝色的圆形绿色的直线

如此,则颜色和形状两个维度可以自由变化,然后进行自由组合即可完成不同颜色的不同形状


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:设计模式(Python语言)----单例模式(python开发设计模式)
下一篇:Spring Cloud + Nacos + Seata整合过程(分布式事务解决方案)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~