设计模式之装饰模式精讲

发布于:2024-04-03 ⋅ 阅读:(122) ⋅ 点赞:(0)

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

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

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

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站:

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


网站公告

今日签到

点亮在社区的每一天
去签到