【设计模式】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()
相关推荐
老蒋每日coding12 分钟前
AI Agent 设计模式系列(十三)—— 人机协同模式
人工智能·设计模式·langchain
老蒋每日coding1 小时前
AI Agent 设计模式系列(十二)—— 异常处理和恢复模式
人工智能·设计模式
小码过河.2 小时前
设计模式——抽象工厂模式
设计模式·抽象工厂模式
国强_dev15 小时前
量体裁衣在技术方案中的应用
设计模式·系统架构
Engineer邓祥浩17 小时前
设计模式学习(16) 23-14 命令模式
学习·设计模式·命令模式
Maddie_Mo18 小时前
智能体设计模式 第二章:路由模式
设计模式
一条闲鱼_mytube21 小时前
智能体设计模式(五)人机协同-知识检索RAG-智能体间通信
网络·人工智能·设计模式
小码过河.21 小时前
设计模式——建造者模式
单片机·设计模式·建造者模式
小码过河.1 天前
设计模式——工厂方法模式
设计模式·工厂方法模式
把csdn当日记本的菜鸡1 天前
Java设计模式简单入门
java·开发语言·设计模式