【设计模式】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()
相关推荐
茶本无香17 分钟前
设计模式之二—原型模式:灵活的对象克隆机制
java·设计模式·原型模式
GISer_Jing40 分钟前
Nano Banana+LoveArt三大核心功能解析:重构AI设计全链路,让创意落地更高效
人工智能·设计模式·aigc
会员果汁2 小时前
14.设计模式-备忘录模式
设计模式·备忘录模式
xiaolyuh12312 小时前
Spring 框架 核心架构设计 深度详解
spring·设计模式·spring 设计模式
GISer_Jing1 天前
智能体工具使用、规划模式
人工智能·设计模式·prompt·aigc
GISer_Jing1 天前
AI Agent:学习与适应、模型上下文协议
人工智能·学习·设计模式·aigc
小马爱打代码1 天前
MyBatis设计模式:构建者、工厂、代理模式
设计模式·mybatis·代理模式
月明长歌1 天前
Javasynchronized 原理拆解:锁升级链路 + JVM 优化 + CAS 与 ABA 问题(完整整合版)
java·开发语言·jvm·安全·设计模式
会员果汁1 天前
12.设计模式-状态模式
设计模式·状态模式
Yu_Lijing1 天前
基于C++的《Head First设计模式》笔记——抽象工厂模式
c++·笔记·设计模式