brief introduction
Decoration mode: dynamically attach responsibilities to objects. To extend functions, decorators provide more flexible alternatives than inheritance.
Advantage
It can not only expand the original functions, but also prevent the explosive growth of classes.
shortcoming
This is more flexible than inheritance, but also means more complexity. Decoration pattern will lead to many small classes in the design, if overused, it will make the program very complex.
Application scenario
1. Add responsibilities to a single object in a dynamic and transparent way without affecting other objects.
2. You need to add functions to an object dynamically, and these functions can also be revoked dynamically. When the system cannot be extended by inheritance or inheritance is not conducive to system expansion and maintenance.
The code is as follows:
#include <iostream> #include <string> #include <string.h> #include <memory> class phone_base { public: virtual void show_decorate(void) = 0; }; //Mi phones class xiaomi : public phone_base { public: virtual void show_decorate(void) { std::cout << "xiaomi : show_decorate ." << std::endl; } }; //HUAWEI mobile phone class huwei : public phone_base { public: virtual void show_decorate(void) { std::cout << "huwei : show_decorate ." << std::endl; } }; //Decoration class class decorator_phone : public phone_base { private: std::shared_ptr<phone_base> m_phone; public: decorator_phone(std::shared_ptr<phone_base> phone): m_phone(phone) {} virtual void show_decorate() { m_phone->show_decorate(); } }; //Specific decoration class - Pendant class decorator_phone_pendant : public decorator_phone { public: decorator_phone_pendant(std::shared_ptr<phone_base> phone) : decorator_phone(phone) {} void show_decorate() { decorator_phone::show_decorate(); add_decorate(); } private: void add_decorate() { std::cout << "add pendant ." << std::endl; } }; //Specific Decoration - film class decorator_phone_film : public decorator_phone { public: decorator_phone_film(std::shared_ptr<phone_base> phone) : decorator_phone(phone) {} void show_decorate() { decorator_phone::show_decorate(); add_decorate(); } private: void add_decorate() { std::cout << "add film ." << std::endl; } }; int main() { std::cout << "start-up .." << std::endl; std::shared_ptr<phone_base> phone = std::make_shared<xiaomi>(); std::shared_ptr<phone_base> phone_pendant = std::make_shared<decorator_phone_pendant>(phone);//Add Pendant std::shared_ptr<phone_base> phone_pendant_film = std::make_shared<decorator_phone_film>(phone_pendant);//Add film phone_pendant_film->show_decorate(); std::cout << "done .." << std::endl; return 0; }
The code runs as follows: