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.



  • 相关阅读:
    jQuery1.3.2 源码学习 2 两个重要的正则表达式
    学习 jQuery 4 使用方法选择
    学习 jQuery 6 在 TreeView 中实现全选
    jQuery1.3.2 源码学习4 init 函数分析 2
    学习 jQuery 3 选择器
    学习 jQuery 5 筛选和过滤器
    条款9:在删除选项中仔细选择
    优化3D图形流水线
    指针相减
    浅谈水体的实现
  • 原文地址:https://www.cnblogs.com/lknny/p/5802117.html
Copyright © 2011-2022 走看看