首页 > 其他 > 详细

Design Pattern:装饰者模式

时间:2020-06-21 19:07:50      阅读:53      评论:0      收藏:0      [点我收藏+]

装饰者模式

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

类图

技术分享图片

应用

例子

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

想法

技术分享图片

设计

技术分享图片

代码示例

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类

技术分享图片

正常应用

技术分享图片

自己写一个

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

Design Pattern:装饰者模式

原文:https://www.cnblogs.com/cpaulyz/p/13173360.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!