装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
pointers_syc14 天前
【设计模式】4.装饰器模式
设计模式·装饰器模式
找不到、了21 天前
Java设计模式之<装饰器模式>
java·设计模式·装饰器模式
未既25 天前
java设计模式 -【装饰器模式】
java·设计模式·装饰器模式
贱贱的剑1 个月前
6. 装饰器模式
设计模式·装饰器模式
饕餮争锋1 个月前
设计模式笔记_结构型_装饰器模式
笔记·设计模式·装饰器模式
engchina1 个月前
Python设计模式深度解析:装饰器模式(Decorator Pattern)完全指南
python·设计模式·装饰器模式
里探2 个月前
Django中为api自定义一些装饰器:如参数校验等
python·django·装饰器模式
charlie1145141912 个月前
从C++编程入手设计模式——装饰器模式
c++·设计模式·装饰器模式
Dave_Young2 个月前
上位机开发中的设计模式(3):装饰器模式
设计模式·装饰器模式
颯沓如流星2 个月前
装饰模式(Decorator Pattern)重构java邮件发奖系统实战
java·重构·装饰器模式