FilterInputStream之装饰模式(例)
来源:互联网 发布:王坚 阿里云 编辑:程序博客网 时间:2024/06/12 20:30
FilterInputStream之装饰模式
1.装饰模式
概诉:
允许向一个现有的对象添加新的功能,同时不改变其结构
属于结构型模式,作为现有类的一个包装
原理
1.1 增加一个修饰类包裹原来的类 —— 包裹的方式一般是通过在将原来的对象作为修饰类的构造函数的参数实现装饰类实现新的功能,
1.2 在不需要用到新功能的地方,它可以直接调用原来的类中的方法。
1.3 修饰类必须和原来的类有相同的接口。
2. 利用FilterInputStream实现大小写字母转化(例)
2.1 首先我们创建一个我们自定义的FilterInputStream的子类UpperCaseInputStream,重写其red()方法来实现我们的需求,请看以下代码:
UpperCaseInputStream 类
import java.io.FilterInputStream;import java.io.IOException;import java.io.InputStream;//创建UpperCaseInputStream 类继承于FilterInputStream public class UpperCaseInputStream extends FilterInputStream { //构造方法 protected UpperCaseInputStream(InputStream in) { super(in); } /** * 重写red()方法 */ @Override public int read() throws IOException { int c = super.read(); return c == -1 ? c : Character.toUpperCase((char) c);//判断取出的字符是否小写,如果是,则进行装换 } /** * 重写read(byte[] b, int off, int len)方法 */ @Override public int read(byte[] b, int off, int len) throws IOException { int length = super.read(b, off, len); for (int i = 0; i < length; i++) { b[i] = (byte) Character.toUpperCase((char) b[i]); } return length; }}
main类
import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.Writer;public class Hw { public static void main(String[] args) { try { File file = new File("test.txt"); if(!file.exists()){ file.createNewFile(); } Writer w = new FileWriter(file); w.write("dhflHKLAGhkLHKhl"); w.flush(); InputStream is = new UpperCaseInputStream(new FileInputStream("test.txt")); int c; while ((c = is.read()) != -1) { System.out.print((char) c); } is.close(); w.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
阅读全文
0 0
- FilterInputStream之装饰模式(例)
- FilterInputStream与装饰模式(1)
- java io -- FilterInputStream 与 装饰者模式
- FilterInputStream与装饰模式(2)--BufferedInputStream源码
- Java8 I/O源码-FilterInputStream、FilterOutputStream与装饰器模式
- 【设计模式】之装饰模式(Decorator)
- 设计模式之装饰模式(Decorator)
- 设计模式之 装饰模式(Decorator)
- 设计模式之装饰模式(Decorator)
- 设计模式之装饰模式(笔记)
- 设计模式之装饰(Decorator)模式
- 设计模式之(装饰者模式)
- 设计模式之装饰模式(Decorator)
- 设计模式之装饰模式(Decorator)
- Java IO 之 FilterInputStream/FilterOutputStream
- 装饰模式之半透明装饰模式
- 设计模式之---装饰(decorator)
- Java之装饰模式(Decorator Pattern)
- PopupWindow的简单使用
- LTC-PolygonLighting
- 关于I/O复用之select函数
- main(int argc, char ** argv)形参的理解与使用
- 2017年8月16日提高组T2 疾病
- FilterInputStream之装饰模式(例)
- Android编程权威指南(第2版)—第5章挑战练习
- 菜鸟初学JDK之ArrayList
- C语言实现哈希表查找算法
- POJ 2513 Colored Sticks(字典树+欧拉回路)
- http://www.gezila.com/tutorials/17290.html
- 未知:爱心蜗牛——题解
- Java的Swing应用中使用JavaFX的功能
- Windows环境Node.JS入坑指南——环境搭建