zoukankan      html  css  js  c++  java
  • 装饰模式/decorator模式/结构型模式

    装饰模式Decorator

    定义

    为对象动态的增加新的功能,实现要求装饰对象和被装饰对象实现同一接口或抽象类,装饰对象持有被装饰对象的实例。

    java实现要点

    1. 定义一个接口或抽象类,作为被装饰者的抽象
    2. 对1定义的抽象,进行具体的实现,作为装饰者,装饰者的构造函数传入1的实例,并持有。
    3. 装饰者对持有的被装饰者进行装饰

    代码示例

    
    //定义共同的接口
    public interface Resizable {  
        public void resize();  
    } 
    //被装饰者为接口的任意实现
    public class Source implements Resizable {  
        @Override  
        public void resize() {  
            System.out.println("the original method!");  
        }  
    } 
    //装饰者对接口的任意实现进行装饰
    public class Decorator implements Resizable {  
        private Resizable source;  
        public Decorator(Resizable source){  //构造器注入被装饰对象
            super();  
            this.source = source;  
        }  
        @Override  
        public void method() {  //实现接口方法,并对被装饰者进行装饰
            System.out.println("before decorator!");  
            source.resize();  
            System.out.println("after decorator!");  
        }  
    }  
    

    JDK中的装饰模式

    java.io包中流的设计,是装饰模式的经典之作。具体为(以输入流为例):

    1. 定义抽象父类InputStream
    2. 然后对InputStream进行具体实现:ByteArrayInputStream、FileInputStream、ObjectInputStream等
    3. 其中FilterInputStream的又有其子类,分别是:BufferedInputStream、DataInputStream等,FilterInputStream什么也没做,仅仅是调用抽象父类InputStream的方法(委托)。
    4. 最终各具体实现类,实现装饰一个InputStream,为它添加它原本不具有的功能。
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("/home/user/abc.txt")));
    //对任意InputStream实现类的装饰
    InputStream in=new BufferedInputStream(new DataInputStream(new ObjectInputStream(new FileInputStream("d:hello.txt"))));
    


    I am a slow walker, but I never walk backwards.



  • 相关阅读:
    文章分类
    多项式笔记(二)
    P7102 [w3R1] 算
    P3711 仓鼠的数学题
    常见特殊数的多项式求法
    P4091 [HEOI2016/TJOI2016]求和
    CF961G Partitions
    P4609 [FJOI2016]建筑师
    P5401 [CTS2019]珍珠
    P5162 WD与积木
  • 原文地址:https://www.cnblogs.com/lknny/p/5802117.html
Copyright © 2011-2022 走看看