大话设计模式学习(一)----装饰模式

大话设计模式学习(三)—-装饰模式C++实现

  • 前面还有简单工厂模式和策略模式,今天先记录装饰模式

一、装饰模式介绍

这里写图片描述
注意这里面涉及到的设计原则
开放-封闭原则(OCP)

Software entities(classes,modules,functions etc) should open for extension ,but close for modification.
什么意思呢?
所谓开放封闭原则就是软件实体应该对扩展开放,而对修改封闭。开放封闭原则是所有面向对象原则的核心。软件设计本身所追求的目标就是封装变化,降低耦合,而开放封闭原则正是对这一目标的最直接体现。
开放封闭原则主要体现在两个方面:
对扩展开放,意味着有新的需求或变化时,可以对现有代码进行扩展,以适应新的情况。
对修改封闭,意味着类一旦设计完成,就可以独立其工作,而不要对类尽任何修改。

二、装饰模式C++实现

  • 环境 win764位 VS2013
  • 场景:小菜穿衣服
类结构实现代码
#include <iostream>
using namespace std;
class person
{
public:
    person(string setName)
    {
        this->name = setName;
    }
    person()
    {}
    virtual void show()
    {
        printf("%s%s\n", "装扮的", name);
    }

private:
    string name;
};

class clothes : public person
{
public:
    void decorate(person *setComponent)
    {
        this->component = setComponent;
    }
    void show()
    {
        if (component)
        {
            component->show();
        }
    }

private:
    person *component = NULL;
};

class TShirts:public clothes
{
public:
    void show()
    {
        cout << "大T恤" << endl;
        clothes::show();
        return;
    }

private:

};

class bigTrouser:public clothes
{
public:
    void show()
    {
        cout << "垮裤" << endl;
        clothes::show();
        return;
    }

private:

};

class shoes : public clothes
{
public:
    void show()
    {
        cout << "球鞋" << endl;
        clothes::show();
        return;
    }
};
测试函数
void testDecorator()
{
    person *xc = new person("小菜");
    TShirts *tx = new TShirts;
    bigTrouser *kk = new bigTrouser;
    shoes *qiuxie = new shoes;

    tx->decorate(xc);
    kk->decorate(tx);
    qiuxie->decorate(kk);

    qiuxie->show();
}

注意在person类的实现中,需要加上person(){},这个空的构造函数,不然会出错

所有设计模式实现的C++代码我都会传到github上面,之后给出地址

git地址如下
设计模式C++实现代码(不断更新中)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值