java设计模式——装饰者模式

本文介绍了一种常用的软件设计模式——装饰者模式,并通过Java代码示例展示了如何使用该模式为饮料添加不同的装饰物来扩展其功能。此外,还提供了一个将输入流中的大写字母转换为小写字母的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

e5fe615e6671f356e23a6a0b378d51d76f4.jpg

/*
    饮料类
 */
public abstract class Beverage {
    String description="Unknown Beverage";
    public String getDescription(){
        return description;
    }
    public abstract double cost();
}
/*
    浓缩咖啡
 */
public class Espresso extends Beverage {
    public Espresso(){
        description="Espresso";
    }
    public double cost() {
        return 1.99;
    }
}
/*
    混合咖啡
 */
public class HouseBlend extends Beverage {
    public HouseBlend(){
        description="House Blend Coffee";
    }
    public double cost() {
        return 0.89;
    }
}
/*
    装饰器类
 */
public abstract class CondimentDecorator extends Beverage {
    public abstract String getDescription();
}
/*
    摩卡
 */
public class Mocha extends CondimentDecorator {
    Beverage beverage;
    public Mocha(Beverage beverage){
        this.beverage=beverage;
    }
    public String getDescription() {
        return beverage.getDescription()+",Mocha";
    }
    public double cost() {
        return 0.20+beverage.cost();
    }
}
/*
    奶泡
 */
public class Whip extends CondimentDecorator {
    Beverage beverage;
    public Whip(Beverage beverage){
        this.beverage=beverage;
    }
    public String getDescription() {
        return beverage.getDescription()+",Whip";
    }
    public double cost() {
        return 0.30+beverage.cost();
    }
}
/*
    测试类
 */
public class Test {
    public static void main(String[] args){
        Beverage beverage= new Espresso();
        beverage=new Mocha(beverage);
        beverage=new Mocha(beverage);
        beverage=new Whip(beverage);
        System.out.println(String.format("%s\n%f",
                beverage.getDescription(),
                beverage.cost()));
    }
}

f061a61b9704a58d22e3cc7ae8ccf700c14.jpg

装饰者模式在java中的应用:IO

0f8e80a213a62a09b92e10b9b17bbf46738.jpg

编写一个装饰者,把输入流内的大写转化成小写:

public class LowerCaseInputStream extends FilterInputStream {
    public LowerCaseInputStream(InputStream in){
        super(in);
    }
    @Override
    public int read() throws IOException {
        int c=super.read();
        return (c==-1?c:Character.toLowerCase((char)c));
    }
    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int result=super.read(b, off, len);
        for(int i=off;i<off+result;i++){
            b[i]=(byte)Character.toLowerCase((char)b[i]);
        }
        return result;
    }
}

https://blog.youkuaiyun.com/lmj623565791/article/details/24269409

转载于:https://my.oschina.net/u/2286010/blog/3030431

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值