装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
geovindu4 天前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
ximu_polaris6 天前
设计模式(c++)-结构型模式-装饰器模式
c++·设计模式·装饰器模式
Q741_14712 天前
设计模式之装饰器模式 理论总结 C++代码实战
c++·设计模式·装饰器模式
Rsun0455113 天前
7、Java 装饰器模式从入门到实战
java·开发语言·装饰器模式
yaaakaaang18 天前
九、装饰器模式
java·装饰器模式
无籽西瓜a23 天前
【西瓜带你学设计模式 | 第十二期 - 装饰器模式】装饰器模式 —— 动态叠加功能实现、优缺点与适用场景
java·后端·设计模式·软件工程·装饰器模式
砍光二叉树1 个月前
【设计模式】结构型-装饰器模式
设计模式·装饰器模式
短剑重铸之日1 个月前
《ShardingSphere解读》16 改写引擎:如何理解装饰器模式下的 SQL 改写实现机制?
java·数据库·后端·sql·shardingsphere·分库分表·装饰器模式
我爱学习_zwj1 个月前
设计模式-3(装饰器模式)
前端·设计模式·装饰器模式
清水白石0082 个月前
装饰器模式 vs Python 装饰器:同名背后的深度解析与实战融合
数据库·python·装饰器模式