设计模式-装饰器模式

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

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

本质跟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");
    }
}
相关推荐
Tiny_React10 小时前
Claude Code Skills 自优化架构设计
人工智能·设计模式
胖虎114 小时前
iOS中的设计模式(十)- 中介者模式(从播放器场景理解中介者模式)
设计模式·中介者模式·解耦·ios中的设计模式
Geoking.14 小时前
【设计模式】组合模式(Composite)详解
java·设计模式·组合模式
刀法孜然14 小时前
23种设计模式 3 行为型模式 之3.6 mediator 中介者模式
设计模式·中介者模式
Yu_Lijing15 小时前
基于C++的《Head First设计模式》笔记——单件模式
c++·笔记·设计模式
Geoking.15 小时前
【设计模式】外观模式(Facade)详解
java·设计模式·外观模式
点云SLAM15 小时前
C++设计模式之单例模式(Singleton)以及相关面试问题
c++·设计模式·面试·c++11·单例模式(singleton)
GISer_Jing1 天前
AI Agent 目标设定与异常处理
人工智能·设计模式·aigc
蔺太微1 天前
组合模式(Composite Pattern)
设计模式·组合模式
鱼跃鹰飞1 天前
DDD中的防腐层
java·设计模式·架构