【设计模式】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()
相关推荐
资深web全栈开发5 小时前
设计模式之访问者模式 (Visitor Pattern)
设计模式·访问者模式
sg_knight6 小时前
对象池模式(Object Pool)
python·设计模式·object pool·对象池模式
Yongqiang Cheng7 小时前
设计模式:C++ 单例模式 (Singleton in C++)
设计模式·c++ 单例模式
得一录7 小时前
AI Agent的主流设计模式之反射模式
人工智能·设计模式
我爱cope7 小时前
【从0开始学设计模式-1| 设计模式简介、UML图】
设计模式·uml
※DX3906※8 小时前
Java多线程3--设计模式,线程池,定时器
java·开发语言·ide·设计模式·intellij idea
J_liaty18 小时前
23种设计模式一中介者模式
设计模式·中介者模式
郝学胜-神的一滴1 天前
在Vibe Coding时代,学习设计模式与软件架构
人工智能·学习·设计模式·架构·软件工程
九狼1 天前
Flutter SSE 流式响用 Dio 实现 OpenAI 兼容接口的逐 Token 输出
http·设计模式·api
郝学胜-神的一滴1 天前
单例模式:从经典实现到Vibe Coding时代的思考
开发语言·c++·程序人生·单例模式·设计模式·多线程