Decoration mode: Dynamically add some additional responsibilities to an object. In terms of adding functionality, the decoration mode is more flexible than generating subclasses.
Four roles of decoration mode:
Component class: Component
Specific component class: ConereteComponent
Decoration class: Decorator (extended from external class The function of Component class, but for Component, there is no need to know the existence of Decorator)
Specific decorative class: ConcreteDecorator (function to add responsibilities to Component)
Here, people Take dressing modification as an example to implement decoration mode.
Test case:
[code]int main(){ //初始化person(人)组件类Component,如果只有一个ConereteComponent类而不需要抽象的Component类,那么可以直接让Decorator继承具体的Component类。 concretePerson *cp = new concretePerson("Jarrett"); //初始化具体服饰类(装饰类Decorate) concreteTshirts *Tshirts = new concreteTshirts; concreteTrouser *Trouser = new concreteTrouser; concreteShoes *Shoe = new concreteShoes; //concreteSuit *Suit = new concreteSuit; concreteHat *Hat = new concreteHat; //依次进行装饰 Tshirts->decorate(cp); Trouser->decorate(Tshirts); Shoe->decorate(Trouser); //Suit->decorate(Shoe); //显示结果 Shoe->show(); std::cout << std::endl; //再装饰一次查看效果 Hat->decorate(Shoe); Hat->show(); return 0; }
Decoration mode implementation:
[code]//主类 class concretePerson{ private: std::string name;//人名 public: concretePerson(){} concretePerson(std::string n):name(n){} //构造方式 virtual void show()const{ std::cout << name << "'s dress: "; } }; //服饰类(装饰类主类) class Finery: public concretePerson{ protected: concretePerson *cPerson;//重点是维护一个主体类对象 public: void decorate(concretePerson *cp){ cPerson = cp; } void show()const{ if(cPerson != NULL) cPerson->show(); } }; //具体服饰类Tshirts class concreteTshirts: public Finery{ public: void show()const{ Finery::show(); //调用基类方法 std::cout << "Tshirts "; //用此来修饰 } }; //具体服饰类Tshirts class concreteTrouser: public Finery{ public: void show()const{ Finery::show(); //调用基类方法 std::cout << "Trouser "; //用此来修饰 } }; //具体服饰类Tshirts class concreteShoes: public Finery{ public: void show()const{ Finery::show(); //调用基类方法 std::cout << "Shoe "; //用此来修饰 } }; //具体服饰类Tshirts class concreteSuit: public Finery{ public: void show()const{ Finery::show(); //调用基类方法 std::cout << "Suit "; //用此来修饰 } }; //具体服饰类Tshirts class concreteHat: public Finery{ public: void show()const{ Finery::show(); //调用基类方法 std::cout << "Hat "; //用此来修饰 } };
In this way, the original class can be simplified by moving and removing the decorative functions in the class from the main class. It effectively separates the core responsibilities and decoration functions of the class, and can remove repeated decoration logic in related classes.
The above is the content of a brief introduction to the decoration mode of C++ design patterns, and more For related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!