装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责。就增加功能来说,此模式比生成子类更为灵活。
/*装饰者模式*/ class Car { public: virtual void show() = 0; }; class RunCar : public Car { public: virtual void show() { cout<<"可以跑"<<endl; } }; class SwimCarDirector : public Car { public: SwimCarDirector(Car *car) { m_car = car; } void swim() { cout<<"可以游泳"<<endl; } virtual void show() { m_car->show(); swim(); } private: Car *m_car; }; class FlyCarDirector : public Car { public: FlyCarDirector(Car *car) { m_car = car; } void fly() { cout<<"可以飞"<<endl; } virtual void show() { m_car->show(); fly(); } private: Car *m_car; };