`
prowl
  • 浏览: 79194 次
  • 性别: Icon_minigender_1
  • 来自: 艾泽拉斯
社区版块
存档分类
最新评论

装饰者模式(decorator)--给爱用继承的人一个全新的设计眼界

阅读更多


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

设计原则:对扩展开放,对修改关闭。


jdk中io采用了这种设计模式,来看一下io的类图先。



FilterInputStream作为一个抽象的装饰者,他的子类可将被装饰者进行包装。

现在我们需要将输入的内容全部转换为大写,来设计扩展这样一个装饰者。


/**
 * @author edison
 * @date 2009-9-25
 */
public class UpperCaseFileInputStream extends FilterInputStream{
	
	FileInputStream fis=null;
	
	protected UpperCaseFileInputStream(InputStream in) {
		super(in);
		fis=(FileInputStream)in;
	}
	
	public UpperCaseFileInputStream(File f) throws FileNotFoundException{
		this(new FileInputStream(f));
	}
	
	public int readForUpperCase(byte[] b){
		int tmp = 0;
		try {
			fis.read(b);
			/**
			 * FilterInputStream里实现了这样一个read方法,
			 * 所以我们也可以直接用父类的read方法。
			 * 这里用fis.read()是为了更好的展示装饰者模式。
			 */
			//read(b);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		for(int i=0;i<b.length;i++){
			b[i]=(byte)Character.toUpperCase((char)b[i]);
		}
		
		return tmp;
	}
}


测试类如下:


/**
 * @author edison
 * @date 2009-9-25
 */
public class TestMyInputStream {
	
	public static void main(String[] args) throws IOException{
		
		File file=new File("C:\\Users\\yang\\Desktop\\abc");
		UpperCaseFileInputStream ucfis=new UpperCaseFileInputStream(file);

		byte[] b=new byte[(int)file.length()];
		int tmp=ucfis.readForUpperCase(b);
		String str=new String(b);
		
		System.out.print("the file's content is: "+str);
		
		ucfis.close();
	}
}


UpperCaseFileInputStream对FileInputStream进行了有效的扩展,遵循了修改关闭,扩展开放的设计原则。

当然,在这里FilterInputStream作为一个抽象的装饰者也实现了一些被装饰者的方法,在这里为了更加清晰的展示装饰者模式并没有直接使用父类方法。


  • 大小: 124.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics