装饰者模式

作者: Stephenwish | 来源:发表于2020-07-23 21:11 被阅读0次

装饰者本质是JAVA继承的一种变种,可以理解为加强的extends


第一步,写个抽象类和继承类
public abstract class MySource {
    abstract void operate();
}

public class MySourceImpl extends  MySource{
    @Override
    void operate() {
        System.err.println("我是具体实现类");
    }
}
第二步,再来一个继承类,不过是没有实现的,里面要放最开始抽象父类这个属性,通过构造注入留个后门装载上面正真的实现类
public abstract class MyOtherSource extends  MySource{
    private MySource mySource=null;

    public MyOtherSource(MySource mySource) {
        this.mySource = mySource;
    }

    @Override
    void operate() {
        mySource.operate();
    }

    //新增几个原始父类没有的方法,再具体的子类实现它
    abstract void stop();
}
第三步,实现上面步骤的实例
public class XOtherSourceImpl extends  MyOtherSource{

    public XOtherSourceImpl(MySource mySource) {
        super(mySource);
    }

    @Override
    void stop() {
        System.err.println("X实现方法");
    }
}

public class YOtherSourceImpl extends MyOtherSource{
    public YOtherSourceImpl(MySource mySource) {
        super(mySource);
    }

    @Override
    void stop() {
        System.err.println("Y实现方法");
    }
}
场景实用类检测
public class Client {
    public static void main(String[] args) {
        MySource mySource = new MySourceImpl();
        MyOtherSource otherSource = new XOtherSourceImpl(mySource);
        otherSource.stop();//相当于在MySourceImpl 里面加了stop 扩展一样
        otherSource.operate();
    }
}

相关文章

  • 如何利用装饰者模式在不改变原有对象的基础上扩展功能

    目录 什么是装饰者模式 普通示例 装饰者模式示例 类图关系 装饰者模式使用场景 装饰者模式优点 装饰者模式缺点 什...

  • 装饰者模式

    装饰者模式 装饰者模式和适配器模式对比 装饰者模式 是一种特别的适配器模式 装饰者与被装饰者都要实现同一个接口,主...

  • java IO 的知识总结

    装饰者模式 因为java的IO是基于装饰者模式设计的,所以要了解掌握IO 必须要先清楚什么事装饰者模式(装饰者模式...

  • 设计模式-装饰者模式

    装饰者模式概念: 装饰者模式又名包装(Wrapper)模式。装饰者模式以对客户端透明的方式扩展对象的功能,是继承关...

  • java - 装饰者模式

    装饰者模式 装饰者模式:动态将责任添加到对象上。如果需要扩展功能,装饰者提供了比继承更有弹性的解决方案。装饰者模式...

  • 设计模式之装饰者模式(Decorator Pattern)

    What: 装饰者模式又名包装(Wrapper)模式。装饰者模式动态地将责任附加到对象身上。若要扩展功能,装饰者提...

  • 装饰者(Decorator)模式

    装饰者(Decorator)模式装饰模式又名包装(Wrapper)模式。装饰模式是继承关系的一个替代方案。装饰模式...

  • 2、装饰者模式

    装饰者模式 一、基本概念 二、结构 三、案例1、装饰者模式案例2、JavaIO中使用装饰者模式 四、总结 一、基本...

  • PHP的设计模式-装饰者模式

    装饰者模式 装饰者模式 装饰者模式类似蛋糕,有草莓味、奶酪等种类,但是它们的核心都是蛋糕。 不断地将对象添加装饰的...

  • 设计模式 | 装饰者模式及典型应用

    前言 本文的主要内容: 介绍装饰者模式 示例 源码分析装饰者模式的典型应用Java I/O 中的装饰者模式spri...

网友评论

    本文标题:装饰者模式

    本文链接:https://www.haomeiwen.com/subject/ochklktx.html