设计模式之装饰模式精讲

本文介绍了装饰器模式,通过例子展示了如何在不改变接口的情况下,为对象添加额外功能,如美国咖啡加糖和奶的装饰。视频讲解资源也提供给读者参考。
摘要由CSDN通过智能技术生成

概念:动态地给一个对象添加一些额外的职责。

装饰器模式侧重于在不改变接口的前提下动态地给对象添加新功能,保持对象结构的透明性,客户端无感知。

以一个咖啡制作和装饰的例子来帮助大家理解:

public interface Coffee {
    double cost();
    String description();
}

public class AmericanCoffee implements Coffee {
    @Override
    public double cost() {
        return 2.5;
    }
    @Override
    public String description() {
        return "纯美式";
    }
}

public abstract class CoffeeDecorator implements Coffee {
    abstract Coffee getCoffee();
}

public class SugarDecorator extends CoffeeDecorator {
    private Coffee coffee;
    public SugarDecorator(Coffee coffee) {
        this.coffee = coffee;
    }
    @Override
    public double cost() {
        return coffee.cost() + 0.5;
    }
    @Override
    public String description() {
        return coffee.description() + ", 加糖";
    }
    @Override
    Coffee getCoffee() {
        return this.coffee;
    }
}

public class MilkDecorator extends CoffeeDecorator {
    private Coffee coffee;
    public MilkDecorator(Coffee coffee) {
        this.coffee = coffee;
    }
    @Override
    public double cost() {
        return this.coffee.cost() + 0.6;
    }
    @Override
    public String description() {
        return this.coffee.description() + ", 加奶";
    }
    @Override
    Coffee getCoffee() {
        return this.coffee;
    }
}

public class Demo {
    public static void main(String[] args) {
        AmericanCoffee americanCoffee = new AmericanCoffee();
        System.out.println(americanCoffee.cost());
        System.out.println(americanCoffee.description());
        System.out.println("********************分割线*****************************");
        SugarDecorator sugarDecorator = new SugarDecorator(americanCoffee);
        System.out.println(sugarDecorator.cost());
        System.out.println(sugarDecorator.description());
        System.out.println("********************分割线*****************************");
        MilkDecorator milkDecorator = new MilkDecorator(sugarDecorator);
        System.out.println(milkDecorator.cost());
        System.out.println(milkDecorator.description());
    }
}

如果大家需要视频版本的讲解,可以关注我的B站:

八、设计模式之装饰模式精讲

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值