zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    剑指offer--12.不用加减乘除做加法
    剑指offer--11.数组中出现次数超过一半的数字
    剑指offer--10.最小的K个数
    剑指offer--9.字符串的排列
    剑指offer--8.调整数组顺序使奇数位于偶数前面
    剑指offer-7.旋转数组的最小数字
    剑指offer--6.数值的整数次方
    剑指offer--5.变态跳台阶
    剑指offer--4.斐波那契数列
    剑指offer--3.用两个栈实现队列
  • 原文地址:https://www.cnblogs.com/cpaulyz/p/13173360.html
Copyright © 2011-2022 走看看