zoukankan      html  css  js  c++  java
  • 装饰者模式(Decorator Pattern)

    装饰者模式(Decorator Pattern):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式比生成子类更加灵活。

     1 #ifndef DECORATOR_H
     2 #define DECORATOR_H
     3 
     4 #include<iostream>
     5 using namespace std;
     6 
     7 class Component
     8 {
     9 public:
    10     virtual void operation()=0;
    11 };
    12 
    13 class ConcreteComponent:public Component
    14 {
    15 public:
    16     void operation()
    17     {
    18         cout<<"ConcreteComponent:operation()"<<endl;
    19     }
    20 };
    21 
    22 class Decorator:public Component
    23 {
    24 protected:
    25     Component* wappedObj;
    26 public:
    27     Decorator(Component* component){
    28         wappedObj=component;
    29     }
    30 };
    31 
    32 class ConcreteDecoratorA:public Decorator
    33 {
    34 public:
    35     ConcreteDecoratorA(Component* component):Decorator(component){}
    36 
    37     void operation()
    38     {
    39         wappedObj->operation();
    40         cout<<"ConcreteDecoratorA:operation()"<<endl;
    41     }
    42 };
    43 
    44 class ConcreteDecoratorB:public Decorator
    45 {
    46 public:
    47     ConcreteDecoratorB(Component* component):Decorator(component){}
    48 
    49     void operation()
    50     {
    51         wappedObj->operation();
    52         cout<<"ConcreteDecoratorB:operation()"<<endl;
    53     }
    54 };
    55 
    56 #endif//DECORATOR_H
    57 
    58 int main()
    59 {
    60 
    61     Component* component=new ConcreteComponent();
    62     component->operation();
    63     cout<<endl;
    64 
    65     component=new ConcreteDecoratorB(component);
    66     component->operation();
    67     cout<<endl;
    68 
    69     component=new ConcreteDecoratorA(component);
    70     component->operation();
    71     cout<<endl;
    72 
    73      return 0;
    74 }
  • 相关阅读:
    UVA 11488 Hyper Prefix Sets (字典树)
    UVALive 3295 Counting Triangles
    POJ 2752 Seek the Name, Seek the Fame (KMP)
    UVA 11584 Partitioning by Palindromes (字符串区间dp)
    UVA 11100 The Trip, 2007 (贪心)
    JXNU暑期选拔赛
    计蒜客---N的-2进制表示
    计蒜客---线段的总长
    计蒜客---最大质因数
    JustOj 2009: P1016 (dp)
  • 原文地址:https://www.cnblogs.com/freewater/p/2561138.html
Copyright © 2011-2022 走看看