装饰器模式

装饰器模式:

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

场景描述:

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

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();

    }
}
相关推荐
丶白泽8 天前
重修设计模式-结构型-装饰器模式
java·设计模式·装饰器模式
心之语歌9 天前
设计模式 装饰模式(Decorator Pattern)
java·设计模式·装饰器模式
Aloha_up9 天前
装饰器模式decorator
装饰器模式
weixin_4177599910 天前
77-java 装饰器模式和适配器模式区别
java·适配器模式·装饰器模式
AI让世界更懂你11 天前
漫谈设计模式 [8]:装饰器模式
python·设计模式·装饰器模式
榴月子14 天前
装饰器模式(Decorator Pattern)
java·开发语言·装饰器模式
犬余15 天前
设计模式之装饰器模式:让对象功能扩展更优雅的艺术
java·设计模式·装饰器模式
磊-15 天前
七、装饰器模式
装饰器模式
miss writer17 天前
装饰器模式及应用【理论+代码】
java·开发语言·装饰器模式
wjs040619 天前
从面向对象(OOP)到面向切面(AOP):编程范式的演变
前端·装饰器模式·aop·面向切面编程·模块化设计·代码复用