装饰者模式

代码详解:【设计模式】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 里的缓存:

相关推荐
逸狼27 分钟前
【JavaEE进阶】Spring DI
java·开发语言
yonuyeung31 分钟前
代码随想录算法【Day54】
java·数据结构·算法
敲上瘾37 分钟前
基础dp——动态规划
java·数据结构·c++·python·算法·线性回归·动态规划
my_styles1 小时前
2025-alibaba-Sentinel组件
java·开发语言·sentinel
Dongwoo Jeong1 小时前
类型系统下的语言分类与类型系统基础
java·笔记·python·lisp·fortran·type
肖帆咪1 小时前
deepseek自动化代码生成
java·ai·自动化·ai编程·deepseek
刘小炮吖i1 小时前
Java 集合:单列集合和双列集合的深度剖析
java·集合
float_六七1 小时前
Java——单例类设计模式
java·单例模式·设计模式
一个儒雅随和的男子1 小时前
Future和FutureTask实现类详解以及使用。
java