设计模式(7)---结构型之装饰模式

1 概念
装饰(Decorator )模式又叫做包装模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。

装饰模式就是把要添加的附加功能分别放在单独的类中,并让这个类包含它要装饰的对象,当需要执行时,客户端就可以有选择地、按顺序地使用装饰功能包装对象。

2适用于:
装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责。就增加功能来说,此模式比生成子类更为灵活。

#ifndef _PHONE_H_
#define _PHONE_H_
class Phone
{
public:
Phone(){}
virtual ~Phone(){}
virtual void ShowPhone() = 0;
};
class NokiaPhone:public Phone
{
public:
NokiaPhone(){}
~NokiaPhone(){}
void ShowPhone();
};
class IPhone :public Phone
{
public:
IPhone(){}
~IPhone(){}
void ShowPhone();
};
class DecoratorPhone :public Phone
{
public:
DecoratorPhone(Phone *ph);
~DecoratorPhone(){}
virtual void ShowPhone() = 0;
private:
Phone *m_ph;
};
class DecoratorPhoneA :public Phone
{
public:
DecoratorPhoneA(Phone *ph);
~DecoratorPhoneA(){}
virtual void ShowPhone();
private:
Phone *m_ph;
};
class DecoratorPhoneB :public Phone
{
public:
DecoratorPhoneB(Phone *ph);
~DecoratorPhoneB(){}
virtual void ShowPhone();
private:
Phone *m_ph;
};
#endif

#include"phone.h"
#include<iostream>
	#include<string>
using namespace std;
void NokiaPhone::ShowPhone()
{
cout << "this is NokiaPhone." << endl;
}
void IPhone::ShowPhone()
{
cout << "this is IPhone." << endl;
}

DecoratorPhoneA::DecoratorPhoneA(Phone *ph)
{
m_ph = ph;
}


void DecoratorPhoneA::ShowPhone()
{
m_ph->ShowPhone();
cout << "ÎÒÒªÌùĤ¡£" << endl;
}
DecoratorPhoneB::DecoratorPhoneB(Phone *ph)
{
m_ph = ph;
}
void DecoratorPhoneB::ShowPhone()
{
m_ph->ShowPhone();
cout << "ÎÒÒª»»¿Ç¡£" << endl;
}

#include"phone.h"
int main()
{
Phone *ph1 = new NokiaPhone;
DecoratorPhoneA *DA = new DecoratorPhoneA(ph1);
DecoratorPhoneB *DB = new DecoratorPhoneB(ph1);
DA->ShowPhone();
DB->ShowPhone();
delete ph1;
delete DA;
delete DB;
return 1;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值