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