装饰者模式:动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
设计原则:对扩展开放,对修改关闭。
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
分享到:
相关推荐
装饰者模式(Decorator Pattern)是一种结构型设计模式,它的定义是在不改变原有对象结构的基础上,动态地给该对象增加一些职责(即增加其额外功能)。这种模式允许向一个现有的对象添加新的功能,同时又不改变其...
设计模式C++学习之装饰模式(Decorator)
decorator-4.2.1-py2.py3-none-any.whl
Head First 设计模式 (三) 装饰者模式(decorator pattern) C++实现 VS2012 下通过
动态地给一个对象添加一些额外的职责。就扩展功能而言,它比生成子类方式更为灵活。
Decorator-3.4.0.tar.gz, a python package
C#设计模式之Decorator 装饰模式,pdf+视频教学,实例演示,易学易用~~
奇幻RPG(物品锻造 与 Decorator模式)本文中,我们通过一个常见的给武器(对象)添加宝石(额外的状态和行为)的例子,讨论了Decorator设计模式的实现过程。
Vue装饰器注入ES6装饰器对Vue.js的依赖注入安装如果您使用的是Webpack或类似产品: npm i --save-dev vue-decorator-inject 否则,-- --save可能更明智。介绍该库将容器与类似于Symfony中的容器的接口结合在一起,并...
NULL 博文链接:https://chuanwang66.iteye.com/blog/1325151
资源来自pypi官网。 资源全名:decorator-4.0.11-py2.py3-none-any.whl
eslint-plugin-decorator-position 一个ESlint插件,它提供一组规则以强制一致的装饰器位置 :red_exclamation_mark: 要求 >= 5 >= 8.5 :rocket: 用法1.安装插件yarn add --dev eslint-plugin-decorator-position ...
官方离线安装包,亲测可用
离线安装包,亲测可用
decorator-4.1.2.tar.gz是支持ipython的依赖包。。。。
资源分类:Python库 所属语言:Python 资源全名:drf_nested_decorator-0.3-py2-none-any.whl 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
decorator-wechat,微信现代化(Nevolution decorator).zip
5、装饰模式(Decorator) 用意:动态地给一个对象增加其它职责,比继承实现灵活。
c++设计模式-结构型模式-装饰器模式;QT工程;...装饰器(Decorator)模式的定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)的模式,它属于对象结构型模式。
python-decorator-3.0.1-3.1.el6.noarch