zoukankan      html  css  js  c++  java
  • 3 装饰模式(1)

    装饰模式

    代码
    1 #include <iostream>
    2 #include <string>
    3
    4  using std::string;
    5  using std::cout;
    6  using std::endl;
    7
    8 class Component
    9 {
    10 public:
    11 virtual void Operation() = 0;
    12 };
    13
    14 class ConcreteComponent : public Component
    15 {
    16 public:
    17 void Operation()
    18 {
    19 cout<<"具体对象的操作"<<endl;
    20 }
    21 };
    22
    23 //装饰抽象类
    24 class Decorator : public Component
    25 {
    26 public:
    27 void SetComponent(Component* component)
    28 {
    29 this->component = component;
    30 }
    31 void Operation()
    32 {
    33 component->Operation();
    34 }
    35 private:
    36 Component* component;
    37 };
    38
    39 //具体装饰类A
    40 class ConcretorDecoratorA : public Decorator
    41 {
    42 public:
    43 void Operation()
    44 {
    45 Decorator::Operation();
    46 addedState = "new state";
    47 cout<<"具体对象A的操作"<<endl;
    48
    49 }
    50 private:
    51 string addedState;
    52 };
    53
    54 //具体装饰类B
    55 class ConcretorDecoratorB : public Decorator
    56 {
    57 public:
    58 void Operation()
    59 {
    60 Decorator::Operation();
    61 AddedBehavior();
    62 cout<<"具体对象B的操作"<<endl;
    63 }
    64 void AddedBehavior()
    65 {
    66 cout<<"具体装饰类B新增加的功能"<<endl;
    67 }
    68 };
    69
    70 int main()
    71 {
    72 //客户端实现
    73 ConcreteComponent* c = new ConcreteComponent();
    74 ConcretorDecoratorA *pa = new ConcretorDecoratorA();
    75 ConcretorDecoratorB *pb = new ConcretorDecoratorB();
    76
    77 pa->SetComponent(c);
    78 pb->SetComponent(pa);
    79 pb->Operation();
    80 return 0;
    81 }
  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/sifenkesi/p/1719633.html
Copyright © 2011-2022 走看看