装饰器模式

装饰器模式:

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

场景描述:

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

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

    }
}
相关推荐
快乐江湖1 天前
「层层包装」—— 装饰器模式
开发语言·python·装饰器模式
likerhood1 天前
设计模式-装饰器模式(java)
java·设计模式·装饰器模式
蜡笔小马5 天前
06.C++设计模式-装饰模式
c++·设计模式·装饰器模式
雪度娃娃8 天前
结构型设计模式——装饰模式
设计模式·装饰器模式
c++之路8 天前
装饰器模式(Decorator Pattern)
java·开发语言·装饰器模式
geovindu25 天前
go:Decorator Pattern
开发语言·设计模式·golang·装饰器模式
ximu_polaris1 个月前
设计模式(c++)-结构型模式-装饰器模式
c++·设计模式·装饰器模式
Q741_1471 个月前
设计模式之装饰器模式 理论总结 C++代码实战
c++·设计模式·装饰器模式
Rsun045511 个月前
7、Java 装饰器模式从入门到实战
java·开发语言·装饰器模式
yaaakaaang1 个月前
九、装饰器模式
java·装饰器模式