装饰者模式(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的时候,这个功能才会执行。

,

posted @ 2016-05-25 16:08  没有梦想的小灰灰  阅读(279)  评论(0编辑  收藏  举报