• Design Pattern:装饰者模式


    装饰者模式

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

    类图

    image-20200620183433869

    应用

    例子

    咖啡类,可以加调料,计算价格

    想法

    image-20200620183447407

    设计

    image-20200620183456429

    代码示例

    public class Mocha extends CondimentDecorator{
    	Beverage beverage;
    	
    	public Mocha(Beverage beverage){
    		this.beverage = beverage;
    	}
    	
    	public String getDescription(){
    		return beverage.description + " Mocha";
    	}
    	
    	public double cost(){
    		return .2+beverage.cost();
    	}
    }
    

    JDK中的装饰者模式

    java.io类

    image-20200620183508418

    正常应用

    image-20200620183518869

    自己写一个

    public class LowerCaseInputStream extends FilterInputStream {
        /**
         * Creates a <code>FilterInputStream</code>
         * by assigning the  argument <code>in</code>
         * to the field <code>this.in</code> so as
         * to remember it for later use.
         *
         * @param in the underlying input stream, or <code>null</code> if
         *           this instance is to be created without an underlying stream.
         */
        protected LowerCaseInputStream(InputStream in) {
            super(in);
        }
    
        //读取当前流中的下一个字节、并以整数形式返回、若读取到文件结尾则返回-1。
        public int read() throws IOException {
            int c = super.read();
            return c==-1?c:Character.toLowerCase(c);
        }
    
        //将当前流中的len个字节读取到从下标off开始存放的字节数组b中。
        public int read(byte b[], int off, int len) throws IOException {
            int res = super.read(b,off,len);
            for(int i = off;i<off+res;i++){
                b[i] = (byte)Character.toLowerCase(b[i]);
            }
            return res;
        }
    
    }
    

    测试

    public class InputTest {
        public static void main(String[] args) {
            int c;
            try {
                InputStream in = new LowerCaseInputStream(new BufferedInputStream(new ByteArrayInputStream("HAHAHAH".getBytes())));
                while ((c=in.read())>=0){
                    System.out.print((char)c);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    

    输出hahahah

  • 相关阅读:
    2020 年最棒的 9 个 Java 框架,哪个最香?
    CTO:不要在 Java 代码中写 set/get 方法了,逮一次罚款
    面试常考:Java中synchronized和volatile有什么区别?
    树莓派3B装ubuntu server后开启wifi
    转:程序内存空间(代码段、数据段、堆栈段)
    环境变量IFS
    python之格式化字符串速记整理
    logging模块简单用法
    理解正则表达式的匹配关系
    cut和tr命令的联合使用
  • 原文地址:https://www.cnblogs.com/cpaulyz/p/13173360.html
Copyright © 2020-2023  润新知