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