装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
清水白石0087 天前
装饰器模式 vs Python 装饰器:同名背后的深度解析与实战融合
数据库·python·装饰器模式
cuber膜拜19 天前
Tenacity 原理与基本使用
服务器·网络·python·装饰器模式·tenacity
短剑重铸之日1 个月前
《设计模式》第六篇:装饰器模式
java·后端·设计模式·装饰器模式
懵萌长颈鹿1 个月前
装饰器模式 (Decorator Pattern)
装饰器模式
进击的小头1 个月前
创建型模式:装饰器模式(C语言实战指南)
c语言·开发语言·装饰器模式
小码过河.1 个月前
17装饰器模式
开发语言·python·装饰器模式
茶本无香1 个月前
设计模式之七—装饰模式(Decorator Pattern)
java·设计模式·装饰器模式
obDLaSfLKr1 个月前
Canoe-Autosar网络管理测试脚本用例CAPL 这适用于Autosar NM主流测试用...
装饰器模式
Geoking.2 个月前
【设计模式】装饰者模式详解
设计模式·装饰器模式
蔺太微2 个月前
装饰器模式(Decorator Pattern)
设计模式·装饰器模式