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 }
  • 相关阅读:
    eclipse安装插件最简单的方法!!
    mysql数据库导入sql文件的方法。
    拿起丢掉的东西,才叫做坚持。
    个人总结作业
    黄金点游戏程序注解
    结对项目的完成与体会
    第三周任务学习记录
    vs2013的安装与使用 测试
    习题作业
    对于四则运算编程自己的过程问题
  • 原文地址:https://www.cnblogs.com/sifenkesi/p/1719633.html
Copyright © 2011-2022 走看看