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 }
  • 相关阅读:
    10分钟学会Python
    Python接口自动化(二)接口开发
    Python接口自动化(一)接口基础
    去掉webstorm内容区域右侧的一条竖线
    webstorm识别element-ui的标签
    vue中点击复制粘贴功能 clipboard 移动端
    vue pc element-ui class
    禁止浏览器记住密码
    js 将网络图片格式转为base64 canvas 跨域
    移动端网页在本地服务器调试
  • 原文地址:https://www.cnblogs.com/freewater/p/2561138.html
Copyright © 2011-2022 走看看