您的位置:首页 > 编程语言 > C语言/C++

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

2016-03-16 16:34 316 查看

大话设计模式学习(三)—-装饰模式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++实现代码(不断更新中)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息