装饰模式

装饰模式,类图:

  1. 部件 (Component) 声明封装器和被封装对象的公用接口。
  2. 具体部件 (Concrete Component) 类是被封装对象所属的类。 它定义了基础行为, 但装饰类可以改变这些行为。
  3. 基础装饰 (Base Decorator) 类拥有一个指向被封装对象的引用成员变量。 该变量的类型应当被声明为通用部件接口, 这样它就可以引用具体的部件和装饰。 装饰基类会将所有操作委派给被封装的对象。
  4. 具体装饰类 (Concrete Decorators) 定义了可动态添加到部件的额外行为。 具体装饰类会重写装饰基类的方法, 并在调用父类方法之前或之后进行额外的行为。
  5. 客户端 (Client) 可以使用多层装饰来封装部件, 只要它能使用通用接口与所有对象互动即可。
#include "iostream"

using namespace std;

// 部件
class Component_CS {
public:
    virtual ~Component_CS() {}
    //const表示this是一个指向常量的指针,=0表示这个成员函数是纯虚函数
    // https://blog.csdn.net/weixin_45525272/article/details/105840562
    virtual void fire() const = 0;
};

// 具体部件
class ConcreteComponent_CS :public Component_CS
{
public:
    ConcreteComponent_CS() {}
    virtual ~ConcreteComponent_CS() {}
    virtual void fire() const
    {
        cout << "反恐精英:" << endl;
    }
    // void fire() const override
    // {
    //     cout<<"反恐精英:"<<endl;
    // }
    // 如果没有实例化,就需要加上virtual or override
    // void fire() const
    // {
    //     cout<<"反恐精英:"<<endl;
    // }
};

//基础装饰
class Weapon : public Component_CS
{
protected:
    Component_CS * person;
public:
    Weapon() {}
    virtual ~Weapon() {}
    //装饰函数
    void Decorate(Component_CS * p)
    {
        person = p;
    }
    virtual void fire() const
    {
        person->fire();
    }
};


//具体装饰
class Ak47 : public Weapon
{
public:
    virtual void fire() const
    {
        Weapon::fire();
        cout << "AK47射击" << endl;
    }
};

//具体装饰
class Pistol : public Weapon
{
public:
    virtual void fire() const
    {
        Weapon::fire();
        cout << "手枪射击" << endl;
    }
};

//具体装饰
class Dagger : public Weapon
{
public:
    virtual void fire() const
    {
        Weapon::fire();
        cout << "捅你" << endl;
    }
};


int main()
{
    Component_CS * person = new ConcreteComponent_CS();
    Weapon * ak = new Ak47();
    Weapon * pistol = new Pistol();
    Weapon * dagger = new Dagger();

    ak->Decorate(person);
    pistol->Decorate(ak);
    dagger->Decorate(pistol);

    dagger->fire();

    getchar();
    return 0;
}

输出:

反恐精英:
AK47射击
手枪射击
捅你




参考:

https://www.guyuehome.com/37133

posted @   double64  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示