• 装饰者模式(Decorator Pattern)


    装饰者模式:动态地将责任附加到对象上,若要扩展功能,装饰者提供比继承更有弹性的替代方案。

    下面来看个具体的例子

    在java.io中就有使用到装饰者模式,下面是类图,注意,类图中的具体组件和装饰者仅列出部分,java中还有其他的具体组件和装饰者没有画出来,仅画出例子中需要用到的类。

    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FilterInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class LowerCaseInputStream extends FilterInputStream {
    
        protected LowerCaseInputStream(InputStream in) {
            super(in);
        }
        public int read() throws IOException {
            int c = super.read();
            return c == -1 ? c : Character.toLowerCase((char)c);
        }
        public int read(byte[] b, int offset, int len) throws IOException {
            int result = super.read(b, offset, len);
            for(int i = offset; i < offset + result; i++) {
                b[i] = (byte)Character.toLowerCase((char)b[i]);
            }
            return result;
        }
        
        public static void main(String[] args) {
            int c;
            try {
                InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
    //设置FileInputStream,先用
    //BufferedInputStream装饰它,再用我们写的LowerCaseInputStream过滤器装饰它
    while((c = in.read()) >= 0) { System.out.print((char)c); } in.close(); } catch (IOException e) { e.printStackTrace(); } } }

    在这个例子中,FilterInputStream是一个装饰者,LowerCaseInputStream继承它,就可以用来装饰具体组件FileInputStream,注意我们先用了BufferInputStream来装饰,再用LoerCaseInputStream装饰,LowerCaseInputStream扩展了read()方法,加上了将字符转成小写的功能。而且我们可以动态地控制,只有当我们使用了LowerCaseInputStream的时候,这个功能才会执行。

    ,

  • 相关阅读:
    Another option to bootup evidence files
    切莫低估了使用者捍卫个人隐私的强烈意志
    如何验证证书绑定?
    How to verify Certificate Pinning?
    iDevice取证的一大突破
    Do you know how many stuff inside your Google Account?
    Use LiveCD to acquire images from a VM
    完成评论功能
    从首页问答标题到问答详情页
    首页列表显示全部问答,完成问答详情页布局。
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5525969.html
Copyright © 2020-2023  润新知