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

C++ 设计模式之装饰者模式

2016-09-19 15:52 375 查看
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;
}


//运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: