您的位置:首页 > 其它

HeadFirst design pattern笔记-装饰者模式

2013-07-07 12:52 471 查看
装饰者模式:动态地将责任附加到对象上,提供了比继承更有弹性的替代方案

装饰者模式的特点:

1.装饰者和被装饰者有相同的父类

2.可以用一个或者多个装饰者包装一个对象

3.可以在运行时动态地用装饰者来装饰对象

4.装饰者可以在其被装饰者的行为(方法)前/后,加上自己的行为

装饰者与继承的方法不同的是,如果依赖继承,有新的行为时,要修改现有的方法,而装饰者模式不用修改已有的类的方法,直接new一个装饰者去包装这个现有的类就可以了。当然这样也会带来缺点,常常会造成设计中有大量的小类,JAVA的I/O便是这种情况。

Java I/O中装饰者的例子:

new DataInputStream(new BufferedInputStream(bew FileInputStream(xxx)));
DataInputStream和BufferedInputStream都扩展自FilterInputStream

编写自己的IO装饰者:

把输入流内的大写字母转换成小写

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LowerCaseInputStream extends FilterInputStream{

protected LowerCaseInputStream(InputStream in) {
super(in);
}

@Override
public int read() throws IOException {
int c = super.read();
return (c == -1 ? c : Character.toLowerCase((char)(c)));
}

@Override
public int read(byte[] b, int off, int len) throws IOException {
int result = super.read(b, off, len);
for (int i = off; i < result + off; i++) {
b[i] = (byte)Character.toLowerCase((char)b[i]);
}
return result;

}

}


测试:

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Test {

public static void main(String[] args) throws IOException {
InputStream in = new LowerCaseInputStream(
new BufferedInputStream(
new ByteArrayInputStream("TEST THE STREAM".getBytes())));
int c = 0;
while ((c = in.read()) >= 0) {
System.out.print((char)c);
}
in.close();
}
}


结果:

test the stream
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: