标签:图片 str div new ptr justify void 影响 ret
1) 意图:
动态的给一个对象添加一些额外的职责,相比较通过生成子类添加职责的方法更加灵活
2) 结构:
其中:
3) 适用性:
4) 举例:
1 #include <iostream> 2 #include <list> 3 class Component 4 { 5 public: 6 Component() {} 7 virtual ~Component() {} 8 virtual void Operation() = 0; 9 }; 10 class ConcreteComponent : public Component 11 { 12 public: 13 virtual void Operation() 14 { 15 std::cout << "print by ConcreteComponent" << std::endl; 16 } 17 }; 18 19 class Decorator : public Component 20 { 21 public: 22 Decorator(Component* com) :m_com(com) {} 23 virtual ~Decorator() {} 24 virtual void Operation() = 0; 25 Component* m_com; 26 }; 27 class ConcreteDecoratorA : public Decorator 28 { 29 public: 30 ConcreteDecoratorA(Component* com) :Decorator(com) {} 31 virtual ~ConcreteDecoratorA() {} 32 virtual void Operation() 33 { 34 m_com->Operation(); 35 addState(); 36 } 37 void addState() 38 { 39 std::cout << "addState" << std::endl; 40 } 41 }; 42 class ConcreteDecoratorB : public Decorator 43 { 44 public: 45 ConcreteDecoratorB(Component* com) :Decorator(com) {} 46 virtual ~ConcreteDecoratorB() {} 47 virtual void Operation() 48 { 49 m_com->Operation(); 50 addBehavior(); 51 } 52 void addBehavior() 53 { 54 std::cout << "addBehavior" << std::endl; 55 } 56 }; 57 58 int main() 59 { 60 Component* ptr = new ConcreteComponent(); 61 Component* ptr1 = new ConcreteDecoratorA(ptr); 62 Component* ptr2 = new ConcreteDecoratorB(ptr1); 63 ptr2->Operation(); 64 delete ptr2; 65 delete ptr1; 66 delete ptr; 67 system("pause"); 68 }
标签:图片 str div new ptr justify void 影响 ret
原文地址:https://www.cnblogs.com/ho966/p/12231642.html