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 }
  • 相关阅读:
    异步方法单元测试
    docker常用命令备忘
    MQ消息最终一致性解决方案(转载)
    JAVA学习知识杂烩
    ASP.NET Core快速入门(第2章:配置管理)- 学习笔记(转载)
    NETCore下IConfiguration和IOptions的用法(转载)
    ASP.NET Core 之 Identity 入门(转载)
    vue+elementui+netcore混合开发
    JWT签名与验签
    使用Machin公式计算
  • 原文地址:https://www.cnblogs.com/freewater/p/2561138.html
Copyright © 2011-2022 走看看