---
title: "装饰者模式"
author: "ganjp"
date: "2011-06-27T11:15:17Z"
tags: []
categories: ["企业架构"]
slug: "untitled"
draft: false
lastmod: "2011-06-27T11:15:17Z"
id: 1106214
url: "https://ganjp.iteye.com/blog/1106214"
---

装饰者模式&gt;&gt;&gt;动态地将责任附加到对象上  若要扩展功能，提供了比继承更有弹性的替代方案，那就是组合。

 

这也满足了高效java推荐的方法：尽量用组合来替代继承 

 

装饰者和被装饰者(即被包装的组件)必须是一样的类型，也就是说有共同的超类，为什么呢，因为装饰者必须能取代被装饰者

 

Java/Io系统就是一个典型的装饰器模式

   装饰组件是InputStream  装饰器FilterInputStream  如果要扩展 只需要继承FilterInputStream 重写read()方法就行了

 

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 length) throws IOException{  
        int result = super.read(b, offset, length);  
        for(int i = offset ; i &lt; 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("D://test.txt")));  
            while((c = in.read()) &gt;= 0 ) {  
                System.out.println((char)c);  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}