结构型模式 装饰模式
适用于: 装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责。就增加功能来说,此模式比生成子类更为灵活。
/** * 结构型模式 装饰模式 * 装饰( Decorator )模式又叫做包装模式。 * 通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。 * 装饰模式就是把要添加的附加功能分别放在单独的类中,并让这个类包含它要装饰的对象,当需要执行时,客户端就可以有选择地、按顺序地使用装饰功能包装对象。 * */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> class Car { public: virtual void show() = 0; }; class RunCar: public Car { public: void Run() { std::cout << "可以跑" << std::endl; } virtual void show() override { Run(); } }; class SwimCarDirector: public Car { public: SwimCarDirector(Car *car) { m_car = car; } void swim() { std::cout << "可以游" << std::endl; } virtual void show() override { m_car->show(); swim(); } private: Car *m_car; }; class FlyCarDirector:public Car { public: FlyCarDirector(Car *car) { m_car = car; } void Fly() { std::cout << "可以飞" << std::endl; } virtual void show() override { m_car->show(); Fly(); } private: Car *m_car; }; void mytest() { Car *runcar = nullptr; runcar = new RunCar(); runcar->show(); std::cout << "车开始装饰 swim" << std::endl; SwimCarDirector *swimcar = new SwimCarDirector(runcar); swimcar->show(); std::cout << "车开始装饰 fly" << std::endl; FlyCarDirector *flycar = new FlyCarDirector(runcar); flycar->show(); delete flycar; flycar = nullptr; delete swimcar; swimcar = nullptr; delete runcar; runcar = nullptr; return; } int main() { mytest(); system("pause"); return 0; }
时间: 2024-10-05 06:05:30