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

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

设计原则:对扩展开放,对修改关闭。 [/b][/color]

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

[img]http://dl.iteye.com/upload/attachment/150650/56366597-c448-391a-a53c-ebfa2d6a35a8.jpg[/img]

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作为一个抽象的装饰者也实现了一些被装饰者的方法,在这里为了更加清晰的展示装饰者模式并没有直接使用父类方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值