装饰者模式

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

相关推荐
刀法如飞9 小时前
AI时代:DDD领域驱动建模与Ontology语义建模的区别
java·设计模式·架构
jeffer_liu9 小时前
Spring AI 生产级实战:工具调用
java·人工智能·后端·spring·ai编程
比昨天多敲两行9 小时前
linux 线程概念与控制
java·开发语言·jvm
8Qi89 小时前
LeetCode 75:颜色分类(荷兰国旗问题)—— Java 题解 ✅
java·算法·leetcode·指针·排序
zzhongcy9 小时前
@Transactional 同类内部调用失效 + 两种自代理解决方案
java
AutumnWind042010 小时前
【Intelij IDEA使用手册】
java·ide·intellij-idea
就叫_这个吧11 小时前
Java注解、元注解、自定义注解定义及应用
java·开发语言·注解
Sam_Deep_Thinking11 小时前
聊聊Java中的of
java·开发语言·架构
NE_STOP12 小时前
Docker--管理监控平台的应用
java
爱吃羊的老虎12 小时前
【JAVA】python转java:Spring Boot 入门
java·spring boot·python