[设计模式]<4>. C++与装饰模式(decorator pattern)
默默地EEer
原文地址:
http://www.cnblogs.com/hebaichuanyeah/p/5612028.html
装饰模式是指,动态的为一个类增加职责(相对于继承)。
举个栗子,反恐精英(counter strike)需要装备突击步枪(AK47),手枪(pistol)和匕首(dagger)等武器。
通过装饰(Decorate)函数增加对象,并继承"开火"函数函数实现相应功能。
#include "iostream" using namespace std; //传说中的CS类 class CounterStrike { public : CounterStrike(){} virtual ~CounterStrike(){} virtual void fire() { cout<<"反恐精英:"<<endl; } }; //武器挂件类 class Weapon : public CounterStrike { protected: CounterStrike * person; public: Weapon(){} virtual ~Weapon(){} //装饰函数 void Decorate(CounterStrike * p) { person = p; } virtual void fire() { person->fire(); } }; //我去,我是AK class Ak47 : public Weapon { public : virtual void fire() { Weapon::fire(); cout<<"AK47射击"<<endl; } }; //手枪类 class Pistol : public Weapon { public : virtual void fire() { Weapon::fire(); cout<<"手枪射击"<<endl; } }; //匕首类 class Dagger : public Weapon { public : virtual void fire() { Weapon::fire(); cout<<"捅你"<<endl; } }; main() { CounterStrike * person = new CounterStrike(); Weapon * ak = new Ak47(); Weapon * pistol = new Pistol(); Weapon * dagger = new Dagger(); ak->Decorate(person); pistol->Decorate(ak); dagger->Decorate(pistol); dagger->fire(); }