【设计模式】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()
相关推荐
Arva .5 小时前
讲一下 Spring 中用到的设计模式
java·spring·设计模式
繁华似锦respect6 小时前
lambda表达式中的循环引用问题详解
java·开发语言·c++·单例模式·设计模式·哈希算法·散列表
星月IWJ9 小时前
领域驱动设计学习
java·学习·设计模式
_dindong10 小时前
Linux网络编程:Reactor反应堆模式
linux·服务器·网络·设计模式·php
雨中飘荡的记忆11 小时前
Step Builder模式实战
java·设计模式
Eren7Y琳11 小时前
开箱即用构建应用环境:openEuler易获得性深度验证
redis·设计模式·架构
Unstoppable2211 小时前
八股训练营第 39 天 | Bean 的作用域?Bean 的生命周期?Spring 循环依赖是怎么解决的?Spring 中用到了那些设计模式?
java·spring·设计模式
闲人编程12 小时前
微服务API网关设计模式
python·缓存·微服务·设计模式·系统安全·api·codecapsule
__万波__12 小时前
二十三种设计模式(八)--装饰器模式
java·设计模式·装饰器模式
@小白鸽12 小时前
1.2.2结构型设计模式
设计模式