装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
佩奇的技术笔记4 天前
从Java的JDK源码中学设计模式之装饰器模式
java·设计模式·装饰器模式
何中应7 天前
【设计模式-3.5】结构型——装饰器模式
java·设计模式·装饰器模式
秋名RG14 天前
深入理解Java装饰器模式:动态扩展对象功能的优雅之道
java·python·装饰器模式
常某某的好奇心1 个月前
装饰模式(Decorator Pattern)
装饰器模式
lczdyx1 个月前
从Flask到智能体:装饰器模式在AI系统中的架构迁移实践
人工智能·python·语言模型·架构·flask·装饰器模式
星星点点洲1 个月前
【设计模式区别】装饰器模式和适配器模式区别
设计模式·适配器模式·装饰器模式
程序员JerrySUN2 个月前
设计模式每日硬核训练 Day 12:装饰器模式(Decorator Pattern)完整讲解与实战应用
设计模式·装饰器模式
aiden:)2 个月前
星巴克咖啡下单系统:UML 类图解析与代码实现
设计模式·软件工程·uml·装饰器模式
〆、风神2 个月前
装饰器模式与模板方法模式实现MyBatis-Plus QueryWrapper 扩展
mybatis·装饰器模式·模板方法模式
qq_529835352 个月前
装饰器模式:如何用Java打扮一个对象?
java·开发语言·装饰器模式