装饰者模式

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

相关推荐
SamDeepThinking7 分钟前
写了十几年代码,聊聊什么样的人能做好Java开发
java·后端·程序员
凛_Lin~~10 分钟前
安卓实现textview跑马灯效果
android·java
开源盛世!!18 分钟前
4.20-4.22
java·服务器·开发语言
京师20万禁军教头25 分钟前
28面向对象(中级)-封装
java
tERS ERTS37 分钟前
头歌答案--爬虫实战
java·前端·爬虫
识君啊43 分钟前
中小厂数据库事务高频面试题
java·数据库·mysql·隔离级别·数据库事务·acid
少许极端1 小时前
算法奇妙屋(四十八)-单调栈
java·算法·单调栈
学习使我健康1 小时前
Android 本地音乐播放(读取系统媒体库 + MediaPlayer)
java·android-studio
云烟成雨TD1 小时前
Spring AI Alibaba 1.x 系列【33】Human-in-the-Loop(人在回路)演示
java·人工智能·spring
難釋懷1 小时前
Redis服务器端优化-内存划分和内存配置
java·redis·spring