实习之路2--设计模式之装饰者模式的理解(装饰IO流操作)
2018-03-10 21:31
267 查看
和字面理解的差不多,装饰者模式就是用一个或多个类去扩展一个类的行为或状态,也就是扩展一个类的功能。相对于继承来说更加灵活。但要求装饰者和被装饰者要相同的超类型。
附上代码说明:import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class UpperInputstream extends FilterInputStream {
public UpperInputstream(InputStream arg0) throws FileNotFoundException {
super(arg0);
}
//扩展父类的read()方法,使得读取后的字符自动转换为大写模式
public int read() throws IOException {
//通过filter的read()方法读取一个字节的数据
int c = super.read();
//如若不是结尾,则将数据转换为大写字母
return (c==-1?c:Character.toUpperCase(c));
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String [] args) {
int c;
try {
//读取test文本的数据进行输出测试
InputStream in = new UpperInputstream(
new FileInputStream("test.txt"));
while((c = in.read())!= -1) {
System.out.print((char)c);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}test文件:
测试结果:
--麦子
附上代码说明:import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class UpperInputstream extends FilterInputStream {
public UpperInputstream(InputStream arg0) throws FileNotFoundException {
super(arg0);
}
//扩展父类的read()方法,使得读取后的字符自动转换为大写模式
public int read() throws IOException {
//通过filter的read()方法读取一个字节的数据
int c = super.read();
//如若不是结尾,则将数据转换为大写字母
return (c==-1?c:Character.toUpperCase(c));
}
}
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String [] args) {
int c;
try {
//读取test文本的数据进行输出测试
InputStream in = new UpperInputstream(
new FileInputStream("test.txt"));
while((c = in.read())!= -1) {
System.out.print((char)c);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}test文件:
测试结果:
--麦子
相关文章推荐
- 黑马程序员——>第十九天<io流(BufferedWriter-装饰设计模式-流操作规律)>
- 【19】IO流2_读写缓冲区,装饰设计模式,图片拷贝,IO流操作规律及其他
- 黑马程序员——IO流-字符流&装饰设计模式
- 基础_IO流学习笔记_文本文件读取及复制、字符流的缓冲区和装饰设计模式
- GOF23设计模式之装饰模式之理解
- 21-IO流-18-IO流(字符流-缓冲区-装饰设计模式)
- 黑马程序员—字节流+字符流缓冲区(装饰设计)+转换流+IO流操作规律+异常日志+系统信息列表输出
- 我所理解的设计模式(C++实现)——装饰者模式(Decorator Pattern)
- 简单Java代码实例助你通俗易懂的理解什么是装饰(者)设计模式 (Decorator)
- IO流小结之二:IO流的装饰设计模式、字节流的知识点小结以及转换流的应用
- Java中IO流中的装饰设计模式(BufferReader的原理)
- IO流-2.【字符流缓冲区BufferedWriter/BufferedReader】【readLine()方法】【装饰设计模式】【LineNumberReader】
- IO流二:IO流之缓冲区BufferedReader、BufferedWriter、装饰设计模式、LineNumberReader
- IO流2(字符流缓冲区、字节流、装饰设计模式、转换流)
- 黑马程序员_基础_IO流学习笔记_文本文件读取及复制、字符流的缓冲区和装饰设计模式
- 设计模式-装饰模式概述和使用-IO流
- 黑马程序员_IO流——装饰设计模式
- 关于设计模式装饰器、适配器、代理模式的关键点理解
- 深入理解JavaScript系列(29):设计模式之装饰者模式详解
- 深入理解JavaScript系列(29):设计模式之装饰者模式