装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
ZouZou老师9 天前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
__万波__12 天前
二十三种设计模式(八)--装饰器模式
java·设计模式·装饰器模式
老鼠只爱大米19 天前
Java设计模式之装饰器模式详解
java·设计模式·装饰器模式·decorator·java设计模式
兵bing20 天前
设计模式-装饰器模式
设计模式·装饰器模式
IT永勇24 天前
C++设计模式-装饰器模式
c++·设计模式·装饰器模式
小毛驴85024 天前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
Samson Bruce1 个月前
4.装饰器模式(Decorator Pattern)
装饰器模式
WKP94181 个月前
装饰器模式和代理模式
代理模式·装饰器模式
ZHE|张恒1 个月前
设计模式实战篇(六):装饰器模式 —— 让系统具备“可生长能力”的架构思想
设计模式·装饰器模式
欠你一个bug2 个月前
Java设计模式应用--装饰器模式
java·设计模式·装饰器模式