设计模式-装饰器模式

角色:被装饰者接口、被装饰者实现类、装饰者抽象类,装饰者实现类。

装饰者抽象类实现被装饰者接口,并持有一个被装饰者接口类型的对象,在继承的方法中先调用被装饰者对象的方法,再调用装饰者的代码。

本质跟AOP很像,不改变被装饰类,用装饰类来扩展被装饰类的功能。像俄罗斯套娃一样可以不停的叠加装饰器。也可以随时抽取被装饰对象直接调用被装饰对象原方法,实现撤销装饰的功能,如果有多层装饰,可以采用递归方法获取被装饰者。

Java中常用的例子:文件输入流作为被装饰类,

FileInputStream in = new FileInputStream();

它的装饰类有:

缓冲输入流 in = new BufferedInputStream(in)。

字符输入流 Reader reader = new InputStreamReader(in);

字符缓冲输入流 BufferedReader br = new BufferedRead(reader);

所有设计模式的目的都是代码复用和对象解耦

java 复制代码
interface Component {
    void operation();
}

class ConcreteComponent implements Component {
    @Override
    public void operation() {
        System.out.println("Core functionality");
    }
}

abstract class Decorator implements Component {
    protected Component component;
    public Decorator(Component c) {
        this.component = c;
    }
}

class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component c) {
        super(c);
    }
    
    @Override
    public void operation() {
        component.operation();
        addedBehavior();
    }
    
    private void addedBehavior() {
        System.out.println("Added behavior");
    }
}
相关推荐
YHL1 天前
🎯 JavaScript 单例模式(Singleton Pattern)—— 从理论到实战
javascript·设计模式
2401_868534781 天前
网络环境规划核心考点全梳理
网络·设计模式
feiyu_gao1 天前
Cocreation Framework:一套给所有人的 AI 协作思考系统
设计模式·aigc·ai编程
善良勤劳勇敢而又聪明的老杨2 天前
【AI编程系列】MCP 常用设计模式解读
设计模式·ai编程
geovindu2 天前
java: Strategy Pattern
java·开发语言·后端·设计模式·策略模式·行为模式
码匠许师傅3 天前
【设计模式精讲】29.行为型模式总结与对比(Behavioral Patterns Summary)
c++·设计模式·uml
geovindu3 天前
CSharp: Observer Pattern
开发语言·后端·观察者模式·设计模式·c#·.netcore·行为模式
YHHLAI4 天前
NestJS 后端开发实战:从设计模式到 CRUD 全栈
设计模式
2401_868534784 天前
长远目标 Long-term Goal 老题沿用
设计模式·需求分析
吃饱了得干活4 天前
Java设计模式实战:一个支付模块的重构之旅,层层递进理解设计模式精髓
后端·设计模式·架构