装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
_DCG_11 天前
c++常见设计模式之装饰器模式
c++·设计模式·装饰器模式
等一场春雨12 天前
Java设计模式 十 装饰模式 (Decorator Pattern)
java·设计模式·装饰器模式
xweiran15 天前
装饰器模式详解(附代码案例和源码分析)
java·装饰器模式·io流·代码案例
计算机小混子15 天前
C++实现设计模式---装饰器模式 (Decorator)
c++·设计模式·装饰器模式
游客52016 天前
设计模式-结构型-装饰器模式
python·设计模式·装饰器模式
博一波16 天前
【设计模式-结构型】装饰器模式
java·设计模式·装饰器模式
JINGWHALE11 个月前
设计模式 结构型 装饰器模式(Decorator Pattern)与 常见技术框架应用 解析
前端·人工智能·后端·设计模式·性能优化·系统架构·装饰器模式
玉面小君1 个月前
C# 设计模式(结构型模式):装饰器模式
设计模式·c#·装饰器模式
玉面小君1 个月前
C# 设计模式:装饰器模式与代理模式的区别
设计模式·c#·代理模式·装饰器模式
冀晓武1 个月前
C++ 设计模式:装饰模式(Decorator Pattern)
c++·设计模式·装饰器模式