装饰器模式

装饰器模式:

将需要装饰的主方法作为某种参数传递,然后对其进行装饰

场景描述:

假设有一个咖啡店,顾客可以根据自己的喜好选择不同的咖啡和添加不同的配料(比如糖和奶油)。

java 复制代码
public class MyTest {
    public static void main(String[] args) {
        Coffee mycoffee = new MyCoffee();
        DecoratorCoffee sugar = new takeSuger(mycoffee);
        takeCream takeCream = new takeCream(sugar);
        takeCream.getCoffee();
    }
}

interface Coffee {
    void getCoffee();
}

abstract class DecoratorCoffee implements Coffee {
    Coffee coffee;

    public DecoratorCoffee(Coffee coffee) {
        this.coffee = coffee;
    }

    public void getcoffee() {
        coffee.getCoffee();
    }
}

class MyCoffee implements Coffee {

    public void getCoffee() {
        System.out.println("接咖啡");
    }
}

class takeSuger extends DecoratorCoffee {


    public takeSuger(Coffee coffee) {
        super(coffee);
    }

    @Override
    public void getCoffee() {
        System.out.println("加糖");
        super.getcoffee();

    }
}

class takeCream extends DecoratorCoffee {

    public takeCream(Coffee coffee) {
        super(coffee);
    }

    @Override
    public void getCoffee() {
        System.out.println("加奶油");
        super.getcoffee();

    }
}
相关推荐
Geoking.2 天前
【设计模式】装饰者模式详解
设计模式·装饰器模式
蔺太微3 天前
装饰器模式(Decorator Pattern)
设计模式·装饰器模式
moxiaoran57534 天前
使用策略模式+装饰器模式实现接口防重复提交
java·装饰器模式
sxlishaobin4 天前
设计模式之装饰器模式
java·设计模式·装饰器模式
apolloyhl5 天前
Decorator 装饰模式
装饰器模式
崎岖Qiu10 天前
【设计模式笔记23】:长文解析-深刻理解「装饰器模式」
java·笔记·设计模式·装饰器模式
资生算法程序员_畅想家_剑魔18 天前
Java常见技术分享-10-装饰器模式
java·开发语言·装饰器模式
世洋Blog23 天前
装饰器模式实践:告别臃肿的继承链,优雅解耦初始化状态管理
unity·设计模式·c#·装饰器模式
qq192263823 天前
基于NSGA2的多目标车辆路径规划 目标1为受灾点缺货量最大值最小,目标2为需求点最晚送达时间最小
装饰器模式
syt_101323 天前
设计模式之-装饰器模式
设计模式·装饰器模式