设计模式之装饰器模式
装饰器模式
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。
意图:动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
主要解决:一般的,我们为了扩展一个类经常使用继承方式实现,由于继承为类引入静态特征,并且随着扩展功能的增多,子类会很膨胀。
何时使用:在不想增加很多子类的情况下扩展类。
如何解决:将具体功能职责划分,同时继承装饰者模式。
实现如下:
# coding:utf-8 __author__ = "xiaomagua" class Shape(object): def draw(self): print("draw noting...") class Circle(Shape): def draw(self): print("draw circle...") class Rectangle(Shape): def draw(self): print("draw rectangle...") class ShapeDecorator(Shape): decoratedShape = None def __init__(self, decoratedShape): self.decoratedShape = decoratedShape def draw(self): self.decoratedShape.draw() class RedShapeDecorator(ShapeDecorator): def __init__(self, decoratedShape): super().__init__(decoratedShape) def draw(self): self.decoratedShape.draw() self.setRedBorder(self.decoratedShape) def setRedBorder(self, decoratedShape): print("Border Color: Red") circle = Circle() redCircle = RedShapeDecorator(circle) redRectangle = RedShapeDecorator(Rectangle()) print("Circle with normal border") circle.draw() print("\nCircle of red border") redCircle.draw() print("\nRectangle of red border") redRectangle.draw()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南