装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-17-装饰器模式(源码剖析篇)
java·spring·设计模式·装饰器模式·源码分析·io流
AI人工智能+电脑小能手2 天前
大白话说Java设计模式-16-装饰器模式(业务实战篇)
java·设计模式·装饰器模式·功能扩展·动态增强
Mr. zhihao3 天前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
日暮南城故里9 天前
装饰器模式深度解析:从Java IO流源码到实战应用
java·设计模式·装饰器模式
无锡银洲自动化10 天前
烟道测孔自动防堵吹扫装置
装饰器模式
莫得感情 o12 天前
设计模式 08 · 装饰器模式
设计模式·装饰器模式
Qdd182315 天前
专业的半包装修公司
装饰器模式
Qdd182320 天前
靠谱的义乌秦塘名邸装修哪个好
装饰器模式
geovindu1 个月前
CSharp: Decorator Pattern
开发语言·后端·c#·装饰器模式·结构型模式
折哥的程序人生 · 物流技术专研1 个月前
Java 23 种设计模式:从踩坑到精通 | 番外:代理 vs 装饰器 —— Spring AOP 到底用了哪个?
java·代理模式·装饰器模式·java面试·java设计模式·springaop·从踩坑到精通