zoukankan      html  css  js  c++  java
  • 设计模式之三:装饰者模式(java内置)

    装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

    设计原则:类应该对扩展开放,对修改关闭。

    我们的目标是允许类容易扩展,在不修改现有代码的情况下,就可以搭配新的行为。如能实现这样的目标,有什么好处呢?这样的设计具有弹性可以应对改变,可以接受新的功能来应对改变的需求。

    工程名称:DecoratorInJDK   下载目录:http://www.cnblogs.com/jrsmith/admin/Files.aspx   ,DecoratorInJDK.zip

     1 package com.jyu.jdk;
     2 
     3 import java.io.FilterInputStream;
     4 import java.io.IOException;
     5 import java.io.InputStream;
     6 
     7 /**
     8  * 编写一个装饰者,把输入流内的所有大写字符转换成小写。
     9  * @author JRSmith
    10  *
    11  */
    12 public class LowerCaseInputStream extends FilterInputStream {
    13 
    14     public LowerCaseInputStream(InputStream in) {
    15         super(in);
    16     }
    17 
    18     @Override
    19     public int read() throws IOException{
    20         int c = super.read();
    21         return  (c == -1 ? c : Character.toLowerCase((char)c));
    22     }
    23     
    24     public int read(byte[] b, int offset, int len) throws IOException{
    25         int result = super.read(b, offset, len);
    26         for(int i = offset; i < offset + result; i++){
    27             b[i] = (byte)Character.toLowerCase((char)b[i]);
    28         }
    29         return result;
    30     }
    31 }
     1 package com.jyu.test;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.IOException;
     5 import java.io.InputStream;
     6 
     7 import com.jyu.jdk.LowerCaseInputStream;
     8 
     9 public class InputTest {
    10 
    11     /**
    12      * @param args
    13      * @throws IOException 
    14      */
    15     public static void main(String[] args) throws IOException {
    16         int c;
    17         InputStream in = new LowerCaseInputStream(new FileInputStream("src\\test.txt"));
    18         
    19         while((c = in.read()) >= 0){
    20             System.out.print((char)c);
    21         }
    22         
    23         in.close();
    24 
    25     }
    26 
    27 }
  • 相关阅读:
    hdu 2222 Keywords Search
    Meet and Greet
    hdu 4673
    hdu 4768
    hdu 4747 Mex
    uva 1513 Movie collection
    uva 12299 RMQ with Shifts
    uva 11732 strcmp() Anyone?
    uva 1401
    hdu 1251 统计难题
  • 原文地址:https://www.cnblogs.com/damonhuang/p/2685078.html
Copyright © 2011-2022 走看看