专业编程基础技术教程

网站首页 > 基础教程 正文

设计模式-结构型模式-装饰器模式

ccvgpt 2024-08-04 12:15:27 基础教程 10 ℃

装饰器模式是一种结构型设计模式,它允许你在不修改现有对象结构的情况下,动态地向对象添加新的行为。装饰器模式通过将对象封装在装饰器对象中,然后将装饰器对象嵌套在其他装饰器对象中,以此来逐步增强对象的功能。

在装饰器模式中,有以下几个角色:

设计模式-结构型模式-装饰器模式

- 抽象组件(Component):定义了一个抽象接口,用于被装饰器和具体组件实现。

- 具体组件(ConcreteComponent):实现了抽象组件的接口,是被装饰器装饰的对象。

- 抽象装饰器(Decorator):继承自抽象组件,包含一个指向抽象组件的引用,并实现了抽象组件的接口。

- 具体装饰器(ConcreteDecorator):继承自抽象装饰器,可以在具体组件的基础上添加额外的行为。

装饰器模式的核心思想是将对象的行为分离成不同的层次,每个层次都有一个具体的装饰器对象。每个装饰器对象都包含一个指向下一层装饰器对象或具体组件对象的引用。当调用装饰器对象的方法时,它会先调用下一层装饰器对象或具体组件对象的方法,然后再执行自己的额外行为。

// decorator_pattern.cpp

// 运行程序
// gcc decorator_pattern.cpp -o decorator_pattern && ./decorator_pattern

// 结果输出
// Coffee with milk: 12
// Coffee with sugar: 11

#include <iostream>

class Beverage
{
public:
    virtual double cost() = 0;
};

class Coffee : public Beverage
{
public:
    double cost() override
    {
        return 10.0;
    }
};

class CondimentDecorator : public Beverage
{
protected:
    Beverage *beverage;

public:
    CondimentDecorator(Beverage *beverage)
    {
        this->beverage = beverage;
    }

    double cost() override
    {
        return beverage->cost();
    }
};

class Milk : public CondimentDecorator
{
public:
    Milk(Beverage *beverage) : CondimentDecorator(beverage) {}

    double cost() override
    {
        return beverage->cost() + 2.0;
    }
};

class Sugar : public CondimentDecorator
{
public:
    Sugar(Beverage *beverage) : CondimentDecorator(beverage) {}

    double cost() override
    {
        return beverage->cost() + 1.0;
    }
};

int main(int argc, char *argv[])
{
    Beverage *coffee = new Coffee();
    Beverage *coffee_with_milk = new Milk(coffee);
    Beverage *coffee_with_sugar = new Sugar(coffee);

    std::cout << "Coffee with milk: " << coffee_with_milk->cost() << std::endl;   // 输出 12.0
    std::cout << "Coffee with sugar: " << coffee_with_sugar->cost() << std::endl; // 输出 11.0

    delete coffee;
    delete coffee_with_milk;
    delete coffee_with_sugar;

    return 0;
}

最近发表
标签列表