装饰者模式

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

相关推荐
喵手44 分钟前
玩转Java网络编程:基于Socket的服务器和客户端开发!
java·服务器·网络
再见晴天*_*2 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
hdsoft_huge5 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
雨白6 小时前
Java 多线程指南:从基础用法到线程安全
android·java
Hungry_Shark6 小时前
IDEA版本控制管理之使用Gitee
java·gitee·intellij-idea
赛姐在努力.6 小时前
《IDEA 突然“三无”?三秒找回消失的绿色启动键、主菜单和项目树!》
java·intellij-idea
猎板PCB黄浩6 小时前
从废料到碳减排:猎板 PCB 埋容埋阻的绿色制造革命,如何实现环保与性能双赢
java·服务器·制造
ZzzK,6 小时前
JAVA虚拟机(JVM)
java·linux·jvm
西红柿维生素6 小时前
JVM相关总结
java·jvm·算法
coderxiaohan7 小时前
【C++】类和对象1
java·开发语言·c++