1.装饰者模式 Decorator

动态地给一个对象添加一个额外的职责, 就添加功能来说, 装饰模式比生成子类更为灵活。

每个装饰对象的实现和如何使用这个对象分离,  每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。

实例:

人和衣服的装饰关系。

person.h   Person类

#ifndef PERSON_H
#define PERSON_H #include <string>
#include <iostream>
using namespace std; class Person
{
public:
Person();
Person(string name);
void virtual show(); private:
string name; }; #endif // PERSON_H

person.cpp

#include "person.h"

Person::Person()
{
} Person::Person(string name)
{
this->name = name;
} void Person::show()
{
cout << " <-name-> " << name << endl;
}

finery.h

#ifndef FINERY_H
#define FINERY_H #include "person.h" class Finery : public Person
{
public:
Finery();
void Decorate(Person *person);
void show(); protected:
Person *person; }; #endif // FINERY_H

finery.cpp

#include "finery.h"

Finery::Finery()
{
} void Finery::Decorate(Person* person)
{
this->person = person;
} void Finery::show()
{
if(person != NULL)
person->show();
}

tshirts.h 装饰者

#ifndef TSHIRTS_H
#define TSHIRTS_H #include "finery.h" class TShirts : public Finery
{
public:
TShirts();
void show();
}; #endif // TSHIRTS_H

tshirts.cpp

#include "tshirts.h"

TShirts::TShirts()
{
} void TShirts::show()
{
cout << " TShirts " << endl;
Finery::show();
}

bigtrouser.h

#ifndef BIGTROUSER_H
#define BIGTROUSER_H #include "finery.h" class BigTrouser : public Finery
{
public:
BigTrouser();
void show();
}; #endif // BIGTROUSER_H

bigtrouser.cpp

#include "bigtrouser.h"

BigTrouser::BigTrouser()
{
} void BigTrouser::show()
{
cout << " BigTrouser " << endl;
Finery::show();
}

main.cpp

#include <iostream>
#include "tshirts.h"
#include "bigtrouser.h"
#include "person.h" using namespace std; int main()
{
cout << "Hello World!" << endl; Person *person = new Person("kevin"); TShirts *tshirt = new TShirts();
BigTrouser *bigT = new BigTrouser(); tshirt->Decorate(person);
bigT->Decorate(tshirt);
bigT->show(); return 0;
}

最新文章

  1. 创建一个Phone实体,完成多页面的电话簿项目
  2. 关于nagios监控远程服务器对服务器性能影响的测试
  3. MySQL的安装配置
  4. 006 [翻译] Haneke(一个Swfit iOS缓存类)
  5. 封装cookie.js、EventUtil.js、
  6. 1.4.2 solr字段类型--(1.4.2.2)solr附带的字段类型
  7. 【转】angular学习笔记(十四)-$watch(1)
  8. 常用加密算法的Java实现总结(二) ——对称加密算法DES、3DES和AES
  9. php开发环境安装配置(2)-eclipsephp
  10. Oracle 账户被锁定
  11. Python3.5入门学习记录-模块
  12. sql server 修改表结构
  13. OC基础了解篇
  14. “Project &#39;MyFunProject&#39; is not a J2SE 5.0 compliant project.”
  15. 【一天一道LeetCode】#49. Group Anagrams
  16. zigbee_蓝牙_wifi的比较与区别分析
  17. 【PAT】B1065 单身狗(25 分)
  18. django学习~models之查询
  19. wps去除首字母自动大写
  20. hive查询遇到java.io.EOFException: Unexpected end of input stream错误

热门文章

  1. JFinal中Controller的应用
  2. 【问题记录】springmvc国际化问题
  3. who 查看系统登录用户
  4. Viewer 是一款强大的 jQuery 图像浏览插件。
  5. 篇一、安装配置Android Studio
  6. Linux中openmpi配置
  7. Downloading jQuery
  8. 写shader注意的一些报错
  9. LR测试HTTPS
  10. vs重复编译