一、装饰者模式
图解如何不依赖于
Nokia类
,直接用耳机类
本身来返回实例。
二、示例代码
#include <iostream>
using namespace std;
class Phone
{
public:
virtual int cost() = 0;
};
class Nokia : public Phone
{
public:
virtual int cost()
{
return 5000;
}
};
class DecoratePhone : public Phone
{
public:
DecoratePhone(Phone* ph) : _phone(ph) {}
protected:
Phone * _phone;
};
class ScreenProtecterPhone : public DecoratePhone
{
public:
ScreenProtecterPhone(Phone *ph) : DecoratePhone(ph) {}
virtual int cost()
{
return 100 + _phone->cost();
}
};
class HeadSetPhone : public DecoratePhone
{
public:
HeadSetPhone(Phone *ph) : DecoratePhone(ph) {}
virtual int cost()
{
return 200 + _phone->cost();
}
};
int main()
{
Nokia nk;
cout << nk.cost() << endl;
ScreenProtecterPhone sp(&nk);
cout << sp.cost() << endl;
// ScreenProtecterPhone sp2(&sp);
// cout << sp2.cost() << endl;
HeadSetPhone hp(&sp);
cout << hp.cost() << endl;
Phone *p = new HeadSetPhone(new ScreenProtecterPhone(new HeadSetPhone(new ScreenProtecterPhone(new Nokia))));
cout << p->cost() << endl;
return 0;
}
网友评论