zoukankan      html  css  js  c++  java
  • 装饰者模式(Decorator Pattern)

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

    下面来看个具体的例子

    在java.io中就有使用到装饰者模式,下面是类图,注意,类图中的具体组件和装饰者仅列出部分,java中还有其他的具体组件和装饰者没有画出来,仅画出例子中需要用到的类。

    import java.io.BufferedInputStream;
    import java.io.FileInputStream;
    import java.io.FilterInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class LowerCaseInputStream extends FilterInputStream {
    
        protected LowerCaseInputStream(InputStream in) {
            super(in);
        }
        public int read() throws IOException {
            int c = super.read();
            return c == -1 ? c : Character.toLowerCase((char)c);
        }
        public int read(byte[] b, int offset, int len) throws IOException {
            int result = super.read(b, offset, len);
            for(int i = offset; i < offset + result; i++) {
                b[i] = (byte)Character.toLowerCase((char)b[i]);
            }
            return result;
        }
        
        public static void main(String[] args) {
            int c;
            try {
                InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
    //设置FileInputStream,先用
    //BufferedInputStream装饰它,再用我们写的LowerCaseInputStream过滤器装饰它
    while((c = in.read()) >= 0) { System.out.print((char)c); } in.close(); } catch (IOException e) { e.printStackTrace(); } } }

    在这个例子中,FilterInputStream是一个装饰者,LowerCaseInputStream继承它,就可以用来装饰具体组件FileInputStream,注意我们先用了BufferInputStream来装饰,再用LoerCaseInputStream装饰,LowerCaseInputStream扩展了read()方法,加上了将字符转成小写的功能。而且我们可以动态地控制,只有当我们使用了LowerCaseInputStream的时候,这个功能才会执行。

    ,

  • 相关阅读:
    一个人事工资模块
    Delete From 带 inner join
    打开SQL AnyWhere *.db数据库
    开启查询IO操作统计
    一个大数据量表访问优化联动下拉框查询优化
    一个简单的配置文件读取类
    MSSQL2005 双机热备说明
    数据库镜像
    GridView + ObjectDatasource 的一个范例代码
    往带自增长列的数据表中导数据
  • 原文地址:https://www.cnblogs.com/13jhzeng/p/5525969.html
Copyright © 2011-2022 走看看