这个今天又个类似的问题
下面是我的笔记
- /*装饰者设计模式与继承的比较
- MyReader//专门用于读取数据-----继承的结构
- |--MyTextReader
- |--MyBufferTextReader
- |--MyMediaReader
- |--MyBufferMediaReader
- |--MyDataReader
- |--MyBufferDataReader
- class MyBufferReader
- {
- MyBufferReader(MyTextReader text){
- }
- MyBufferReader(MyMediaReader text){
- }
- MyBufferReader(MyDataReader text){
- }
- }
- 该类的扩展性很差,
- 找到其参数的共同类型,通过多态形式通过扩展性
- class MyBufferReader extends MyReader //继承公共父类,即MyReader,而不像继承结构中-继承MyReader的子类
- {
- MyBufferReader(MyReader r){
- }
- }
- MyReader//专门用于读取数据的类-----装饰模式的结构
- |--MyTextReader
- |--MyMediaReader
- |--MyDataReader
- |--MyBufferReader //组合结构
- */
- import java.io.*;
- class MyBufferedReader extends Reader
- {
- private Reader fr = null;
- MyBufferedReader(Reader fr){
- this.fr = fr;
- }
- public String myReadLine() throws IOException{
- StringBuilder sb = new StringBuilder(); //StringBuilder();
- int ch = 0;
- while ((ch = fr.read())!= -1)
- {
- if (ch=='\r')
- continue; // the keyword continue.
- if(ch == '\n')
- return sb.toString();
- sb.append((char)ch);
- }
- if (sb.length() != 0)
- return sb.toString(); //important to return the last line.
-
- return null;
- }
- public int read (char[] buf, int off, int len) throws IOException{
- return read (buf, off, len); //调用对象方法
- }
- public void close() throws IOException{
- fr.close(); //调用对象方法
- }
- public void myClose() throws IOException{
- fr.close();
- }
- }
- class MyBufferedReaderDemo{
- public static void main(String[] args) throws IOException
- {
- FileReader fr = new FileReader("buf.txt");
- MyBufferedReader mr = new MyBufferedReader(fr);
- String line = null;
- while ((line = mr.myReadLine()) != null)
- {
- System.out.println(line);
- }
- System.out.println("Hello World!");
- }
- }
复制代码 毕老师的课程是第19天
装饰和继承的比较 |