码迷,mamicode.com
首页 > 其他好文 > 详细

装饰者模式(Decorator Pattern)

时间:2016-05-25 16:44:00      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

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

 

技术分享

 

下面来看个具体的例子

在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的时候,这个功能才会执行。

,

装饰者模式(Decorator Pattern)

标签:

原文地址:http://www.cnblogs.com/13jhzeng/p/5525969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!