• 设计模式之三:装饰者模式(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 }
  • 相关阅读:
    CSS3 经典教程系列:CSS3 线性渐变(linear-gradient)
    JS定义函数
    CSS选择器和jQuery选择器的区别与联系
    jQuery 选择器、遍历方法
    jQuery中$()函数
    JS对象和Jquery对象
    [Alpha]Scrum Meeting#2
    [Alpha]Scrum Meeting#1
    knowledge_docker
    problems_docker
  • 原文地址:https://www.cnblogs.com/damonhuang/p/2685078.html
Copyright © 2020-2023  润新知