C++ 设计模式之装饰者模式
来源:互联网 发布:知乎 国企校园招聘 编辑:程序博客网 时间:2024/06/05 05:34
1 装饰模式的类图:
2装饰着模式(Decorator): 动态的给一个对象添加一些额外的职责.
比如java.io包. BufferedInputStream封装了FileInputStream, 它们都实现了InputStream接口, 但前者实现了readLine方法.
3 代码实例:
#include<iostream>#include<string>using namespace std;class Phone{public:virtual void ShowDecorator(){};};class NokiaPhone :public Phone{private:string m_name; public:NokiaPhone(string name):m_name(name){}void ShowDecorator(){cout<<m_name <<"’s Decorator"<<endl;}};class iPhone:public Phone{private:string m_name;public:iPhone(string name):m_name(name){}void ShowDecorator(){cout<<m_name <<"’s Decorator"<<endl;}};class DecoratorPhone:public Phone{private:Phone *m_phone; // 要装饰的手机public:DecoratorPhone(Phone *phone):m_phone(phone){}virtual void ShowDecorator(){m_phone->ShowDecorator();}};class DecoratorPhoneA:public DecoratorPhone{private:void AddDecorate(){cout<<" Add GUA JIAN "<<endl;}public:DecoratorPhoneA(Phone *phone):DecoratorPhone(phone){}void ShowDecorator(){DecoratorPhone::ShowDecorator(); AddDecorate();}};class DecoratorPhoneB:public DecoratorPhone{private:void AddDecorate(){cout<<" PING MU Tie Mo "<<endl;}public:DecoratorPhoneB(Phone *phone):DecoratorPhone(phone){}void ShowDecorator(){DecoratorPhone::ShowDecorator(); AddDecorate();}};
//主程序:
// Decorator.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include "PhoneDecorator.hpp"/*装饰者模式*/int _tmain(int argc, _TCHAR* argv[]){Phone *iphone = new iPhone("Apple Phone");iphone->ShowDecorator();cout<<endl;Phone *dqa = new DecoratorPhoneA(iphone);dqa->ShowDecorator();cout<<endl;Phone *dqb = new DecoratorPhoneB(dqa);dqb->ShowDecorator();system("pause");return 0;}
//运行结果:
0 0
- C#--设计模式之装饰者模式
- 设计模式之装饰者设计模式
- 设计模式 之 装饰者
- 设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之Decorator(装饰者模式)
- 设计模式之五---装饰者模式
- 设计模式之---装饰者模式
- c++设计模式之装饰者模式
- Php设计模式之装饰者模式
- java设计模式之装饰者模式
- 设计模式之装饰者模式
- 【设计模式】之装饰者模式
- HeadFirst设计模式之装饰者模式
- c++设计模式之装饰者模式
- 设计模式之装饰者模式
- 设计模式之--装饰者模式
- 设计模式之装饰者模式
- 回到博客
- 防止tableview滚动误点击
- php之xdebug多站点失效问题
- Linux-Ubuntu14.04下JDK+tomcat安装与项目部署图文详解
- 统计学习方法-读书笔记
- C++ 设计模式之装饰者模式
- Java 中 String 类的常用方法 Ⅰ
- 171. Excel Sheet Column Number
- C# 设置和获取一个字节的某一位的值的方法 .
- Oracle的Flashback用法汇总
- HDU 5889 Barricade (单源最短路 + 最小割(最大流))
- Windows-SSD配置与测试
- 序列求和
- android用memtester内存压力测试