10-设计模式——装饰器模式
设计模式——装饰器模式
装饰器模式 ==> Decorator
开闭原则:类应该对扩展开放,对修改关闭:也就是添加新功能时不需要修改代码。(对修改关闭,对扩展开放)
模式定义:
在不改变原有对象的基础上,将功能附加到对象上
为对象动态添加功能。
装饰者(Decorator)和具体组件(ConcreteComponent)都继承自组件(Component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。
所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。
装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。
应用场景:
扩展一个类的功能或给一个类添加附加职责
优点:
- 不改变原有对象的情况下给一个对象扩展功能
- 使用不同的组合可以实现不同的效果
- 符合开闭原则(对修改关闭,对扩展开放)
package com.example.designpatterns.decorator; /** * @program: DesignPatterns * @description: 装饰器模式 * @author: Coder_Pan * @create: 2022-04-13 15:55 **/ public class DecoratorTest { public static void main(String[] args) { System.out.println("装饰器模式......"); System.out.println("_______________原始需求________________"); //原始需求 Component component = new ConcreteComponent(); component.operation(); System.out.println("_______________新增需求1________________"); //新增需求1 ConcreteDecorator concreteDecorator = new ConcreteDecorator(component); concreteDecorator.operation(); System.out.println("_______________新增需求2________________"); //新增需求2 ConcreteDecorator1 concreteDecorator1 = new ConcreteDecorator1(concreteDecorator); concreteDecorator1.operation(); } } interface Component { /** * operation */ void operation(); } class ConcreteComponent implements Component { @Override public void operation() { System.out.println("拍照"); } } /** * 定义Decorator装饰器 */ abstract class Decorator implements Component { /** * 使装饰器持有Component的引用 */ Component component; public Decorator(Component component) { this.component = component; } } /** * 添加滤镜效果 */ class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } @Override public void operation() { System.out.println("添加美颜......"); //调用父级的方法 component.operation(); } } class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(Component component) { super(component); } @Override public void operation() { System.out.println("添加滤镜....."); component.operation(); } }
posted on 2022-04-13 16:11 JavaCoderPan 阅读(12) 评论(0) 编辑 收藏 举报 来源
【推荐】国内首个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代理技术深度解析与实战指南