设计模式-装饰器模式

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

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

本质跟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");
    }
}
相关推荐
蜡笔小马几秒前
13.C++设计模式-策略模式
c++·设计模式·策略模式
therese_100866 分钟前
客户端架构:为什么、什么时候、怎么做
设计模式·安卓·鸿蒙
多加点辣也没关系10 小时前
设计模式-解释器模式
设计模式·解释器模式
Asurplus12 小时前
23中设计模式
设计模式·创建型·结构型·行为型
geovindu13 小时前
go: Semaphore Pattern
开发语言·后端·设计模式·golang·企业级信号量模式
写了20年代码的老程序员18 小时前
写了 20 年 Java,我发现 90% 的 if-null 和 try-catch 其实是因为缺了一条原则
设计模式·ai编程
货拉拉技术21 小时前
私域转化率翻倍的秘密:我们把多模态Agent融进了私域营销
人工智能·算法·设计模式
看山是山_Lau21 小时前
抽象工厂模式:一整套对象族如何统一创建?
设计模式·抽象工厂模式
木易 士心21 小时前
深入理解 OKHttp:设计模式、核心机制与架构优势
android·设计模式·架构