装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
代码萌新知5 天前
设计模式学习(五)装饰者模式、桥接模式、外观模式
java·学习·设计模式·桥接模式·装饰器模式·外观模式
笨手笨脚の7 天前
设计模式-装饰器模式
java·设计模式·装饰器模式·结构型设计模式
charlie11451419110 天前
精读C++20设计模式:结构型设计模式:装饰器模式
笔记·学习·设计模式·程序设计·c++20·装饰器模式
奔跑吧邓邓子13 天前
【C++实战㊹】解锁C++装饰器模式:实战与技巧全解析
c++·实战·装饰器模式
休息一下接着来13 天前
C++ 装饰器模式
c++·设计模式·装饰器模式
bkspiderx13 天前
C++设计模式之结构型模式:装饰器模式(Decorator)
c++·设计模式·装饰器模式
new_daimond1 个月前
设计模式-装饰器模式详解
设计模式·装饰器模式
九术沫1 个月前
装饰器模式在Spring中的案例
java·spring·装饰器模式
o0向阳而生0o1 个月前
102、23种设计模式之装饰器模式(11/23)
设计模式·装饰器模式
宁静致远20211 个月前
【C++设计模式】第五篇:装饰器模式
c++·设计模式·装饰器模式