03: 装饰模式

1. 案例:手机->贴膜->戴保护套->贴卡通贴纸->系手机挂绳

2. 组合模式和装饰模式

组合模式和装饰模式都可以用来透明的把对象包装在具有同样接口的另一个对象中。
组合模式和装饰模式都是结构型模式。组合模式着眼于把众多子对象组织为一个整体;装饰模式着眼于在不修改现有对象或从其派生子类的前提下为其增添职责,其子对象只有一个。

3. 装饰模式结构

- Component(抽象构件):是具有构件类和装饰类的共同基类,声明了在具体构件中定义的方法,客户端可以一致的对待使用装饰前后的对象

class Component
{
public:
    virtual void Operation() = 0;
};

- Decorator(抽象装饰类):用于给具体构件增加职责,但具体职责在其子类中实现。抽象装饰类通过聚合关系定义一个抽象构件的对象,通过该对象可以调用装饰之前构件的方法,并用过其子类扩展该方法,达到装饰的目的

class Decorator:
    public Component
{
public:
    void DecoratorComponent(std::shared_ptr<Component> spComponent);
    // 通过 Component 继承
    void Operation() override;
private:
    std::shared_ptr<Component> m_spComponent;
};

void Decorator::DecoratorComponent(std::shared_ptr<Component> spComponent)
{
    m_spComponent = spComponent;
}

void Decorator::Operation()
{
    m_spComponent->Operation();
}

 - ConcreteComponent(具体构件):具体构件定义了构件具体的方法,装饰类可以给它增加更多的功能

class Phone :
    public Component
{
public:
    // 通过 Decorator 继承
    void Operation() override;
};

void Phone::Operation()
{
    std::cout << "Phone" << std::endl;
}

 - ConcreteDecorator(具体装饰类):向构件增加新的功能

class DecoratorFilm :
    public Decorator
{
public:
    // 通过 Decorator 继承
    void Operation() override;
};

void DecoratorFilm::Operation()
{
    Decorator::Operation();
    std::cout << "贴膜" << std::endl;
}
class DecoratorRope :
    public Decorator
{
public:
    // 通过 Decorator 继承
    void Operation() override;
};

void DecoratorRope::Operation()
{
    Decorator::Operation();
    std::cout << "戴保护壳" << std::endl;
}
class DecoratorShell :
    public Decorator
{
public:
    // 通过 Decorator 继承
    void Operation() override;
};

void DecoratorShell::Operation()
{
    Decorator::Operation();
    std::cout << "贴卡通贴纸" << std::endl;
}
class DecoratorSticker :
    public Decorator
{
public:
    // 通过 Decorator 继承
    void Operation() override;
};

void DecoratorSticker::Operation()
{
    Decorator::Operation();
    std::cout << "系手机挂绳" << std::endl;
}

4. 用法

    std::shared_ptr<Phone> spPhone = std::make_shared<Phone>();
    std::shared_ptr<DecoratorFilm> spDecoratorFilm = std::make_shared<DecoratorFilm>();
    std::shared_ptr<DecoratorShell> spDecoratorShell = std::make_shared<DecoratorShell>();
    std::shared_ptr<DecoratorSticker> spDecoratorSticker = std::make_shared<DecoratorSticker>();
    std::shared_ptr<DecoratorRope> spDecoratorRope = std::make_shared< DecoratorRope>();

    spDecoratorFilm->DecoratorComponent(spPhone);
    spDecoratorShell->DecoratorComponent(spDecoratorFilm);
    spDecoratorSticker->DecoratorComponent(spDecoratorShell);
    spDecoratorRope->DecoratorComponent(spDecoratorSticker);

    spDecoratorRope->Operation();
posted @ 2024-09-16 12:17  博瑜图形  阅读(27)  评论(0)    收藏  举报