【设计模式】01-装饰器模式Decorator

作用:在不修改对象外观和功能的情况下添加或者删除对象功能,即给一个对象动态附加职能

装饰器模式主要包含以下角色。

  1. 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
  2. 具体构件(ConcreteComponent)角色:实现抽象构件,通过装饰角色为其添加一些职责。
  3. 抽象装饰(Decorator)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
  4. 具体装饰(ConcreteDecorator)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的责任。
复制代码
package decorator;
public class DecoratorPattern {
    public static void main(String[] args) {
        Component p = new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d = new ConcreteDecorator(p);
        d.operation();
    }
}
//抽象构件角色
interface Component {
    public void operation();
}
//具体构件角色
class ConcreteComponent implements Component {
    public ConcreteComponent() {
        System.out.println("创建具体构件角色");
    }
    public void operation() {
        System.out.println("调用具体构件角色的方法operation()");
    }
}
//抽象装饰角色
class Decorator implements Component {
    private Component component;
    public Decorator(Component component) {
        this.component = component;
    }
    public void operation() {
        component.operation();
    }
}
//具体装饰角色
class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    public void operation() {
        super.operation();
        addedFunction();
    }
    public void addedFunction() {
        System.out.println("为具体构件角色增加额外的功能addedFunction()");
    }
}

运行结果

复制代码
创建具体构件角色
调用具体构件角色的方法operation()
---------------------------------
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()
相关推荐
玖玥拾3 小时前
C/C++ 基础笔记(十一)类的进阶
c语言·c++·设计模式·
geovindu7 小时前
go: Broadcast Pattern
开发语言·后端·设计模式·golang·广播模式
我爱cope8 小时前
【Agent智能体23 | 规划-规划工作流】
人工智能·设计模式·语言模型·职场和发展
lengjingzju8 小时前
符·形·音·意(SFEM):一种面向通用智能的四维认知架构
设计模式·ai·学习方法
贵慜_Derek10 小时前
《从零实现 Agent 系统》连载 23|Skill 体系与 Skill Creator:能力打包与迭代
人工智能·设计模式·架构
张小姐的猫11 小时前
【Linux】多线程 —— 线程池 | 单例模式 | 常见锁
linux·运维·服务器·c++·单例模式·设计模式·策略模式
老码观察11 小时前
设计模式实战解读(十二):状态模式——干掉状态机里的 if-else 地狱
设计模式·状态模式
我爱cope12 小时前
【Agent智能体24 | 规划-创建和执行LLM计划】
人工智能·设计模式·语言模型·职场和发展
Hillain12 小时前
软件设计师设计模式
java·开发语言·经验分享·笔记·算法·设计模式·软考
zhengfei61121 小时前
第3章 Agent 类型分类与设计模式
设计模式