对扩展开放,对修改关闭
当对一个事物进行抽象的时候,会出现一个父类,很多子类的情况。而且新添加子类时是不容易的,也就是说不易扩展。
装饰者模式可以动态的将职责添加,不影响原来的类
装饰者模式的图示
装饰者模式的组成
1. Component
抽象组件,也叫装饰者的基类。通过基类和多态的应用,才能实现装饰者模式
2. ConcreteComponent
具体组件,又叫被装饰对象,可以动态的给它添加职责
3. Decorator
装饰者抽象类
4. ConcreteDecorator(A,B,C,D....)
具体的装饰者类。可以扩展部分
5 在ConcretComponnet和ConcreteDecorator相同的方法MehtodeA
如下就动态的给fileInputStream 这个实例动态的添加了职责
File file=new File("D:\\tmp\\forIO.txt");
FileInputStream fileInputStream=new FileInputStream(file);
DataInputStream dataInputStream= new DataInputStream(fileInputStream);
BufferedInputStream bufferedInputStream = new BufferedInputStream(dataInputStream);
int n=0;
byte[] b=new byte[2];
=int i=0;
while (n!=-1) //当n不等于-1,则代表未到末尾
{
n=bufferedInputStream.read();
System.out.println("n:"+n);
System.out.println(Arrays.toString(b));
System.out.println("执行次数:"+i);
}
}
1. DataInputStream 中
public final int read(byte b[]) throws IOException {
return in.read(b, 0, b.length);
}
2. FileInputStream 中
public int read(byte b[], int off, int len) throws IOException {
return readBytes(b, off, len);
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。