装饰者模式

代码详解:【设计模式】Java 设计模式之装饰者模式(Decorator)_java 装饰者模式-CSDN博客

java 复制代码
// 抽象构件角色
public interface Component {
    void operation();
}

// 具体构件角色
public class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("执行具体构件对象的操作");
    }
}

// 装饰角色
public class Decorator implements Component {
    protected Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        if (component != null) {
            component.operation();
        }
    }
}

// 具体装饰角色A
public class ConcreteDecoratorA extends Decorator {
    public ConcreteDecoratorA(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunctionA();
    }

    public void addedFunctionA() {
        System.out.println("为构件对象添加功能A");
    }
}

// 具体装饰角色B
public class ConcreteDecoratorB extends Decorator {
    public ConcreteDecoratorB(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunctionB();
    }

    public void addedFunctionB() {
        System.out.println("为构件对象添加功能B");
    }
}

装者模式的应用:

-mybatis 里的缓存:

相关推荐
代码小将1 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点1 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx2 小时前
PYTHON训练营DAY25
java·开发语言·python
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
chxii6 小时前
5java集合框架
java·开发语言
yychen_java7 小时前
R-tree详解
java·算法·r-tree
JANYI20187 小时前
嵌入式设计模式基础--C语言的继承封装与多态
java·c语言·设计模式
xrkhy7 小时前
反射, 注解, 动态代理
java
Ten peaches7 小时前
Selenium-Java版(操作元素)
java·selenium·测试工具·html
lyw2056198 小时前
RabbitMQ,Kafka八股(自用笔记)
java