设计模式-装饰器模式

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

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

本质跟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");
    }
}
相关推荐
咖啡八杯15 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong19 小时前
学习创建结构行为设计模式
设计模式
w_t_y_y21 小时前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式
zhouhui0011 天前
订单状态的 if-else 地狱上线就崩——状态模式的工业级落地
设计模式
geovindu1 天前
go: Reactor Pattern
开发语言·后端·设计模式·golang·反应器模式
一只旭宝1 天前
【C++入门精讲22】常见设计模式
c++·设计模式
折哥的程序人生 · 物流技术专研2 天前
Java 23 种设计模式:从踩坑到精通 | 装饰器模式 —— 比继承更灵活的扩展方式,你用过吗?
java·装饰器模式·java面试·结构型模式·java设计模式·javaio·从踩坑到精通
许彰午2 天前
38_Java设计模式之装饰器模式
java·设计模式·装饰器模式
geovindu2 天前
python: Reactor Pattern
开发语言·python·设计模式·反应器模式
workflower2 天前
基于机器学习的设备故障预测分析方法
人工智能·算法·机器学习·设计模式·语言模型·自然语言处理·重构