zoukankan      html  css  js  c++  java
  • C++模式学习------策略模式

    当遇到同一个对象有不同的行为,方法,为管理这些方法可使用策略模式。

    策略模式就是对算法进行包装,是把使用算法的责任和算法本身分割开来。通常把一个系列的算法包装到一系列的策略类里面,这些类继承一个抽象的策略类。使用这些算法的时候,只需要调用子类即可。

    例如:

     1 class LearnTool
     2 {
     3 public:
     4     void virtual useTool() = 0;
     5 };
     6 
     7 class BookTool:public LearnTool
     8 {
     9 public:
    10     void useTool()
    11     {
    12         cout << "Learn by book !" << endl;
    13     }
    14 };
    15 
    16 class ComputerTool:public LearnTool
    17 {
    18 public:
    19     void useTool()
    20     {
    21         cout << "Learn by computer !" << endl;
    22     }
    23 };
    24 
    25 class Person
    26 {
    27 public:
    28     Person()
    29     {
    30         tool = 0;
    31     }
    32     void setTool(LearnTool *w)
    33     {
    34         this->tool = w;
    35     }
    36     void virtual Learn() = 0;
    37 protected:
    38     LearnTool *tool;
    39 };
    40 
    41 class Tom:public Person
    42 {
    43 public:
    44     void Learn()
    45     {
    46         cout << "The Tom:" ;
    47         if ( this->tool == NULL)
    48         {
    49             cout << "You have`t tool to learn !" << endl;
    50         }
    51         else
    52         {
    53             tool->useTool();
    54         }
    55     }
    56 };
    57 int main()
    58 {
    59     LearnTool *book = new BookTool();
    60     LearnTool *computer = new ComputerTool();
    61 
    62     Person *tom = new Tom();
    63 
    64     tom->Learn();
    65     cout << endl;
    66 
    67     tom->setTool(book);
    68     tom->Learn();
    69     cout << endl;
    70 
    71     tom->setTool(computer);
    72     tom->Learn();
    73 
    74     return 0;
    75 }
  • 相关阅读:
    ***php 数组添加关联元素的方法小结(关联数组添加元素)
    阿里云PHP Redis代码示例
    linux内核编程笔记【原创】
    linux RTC 驱动模型分析【转】
    linux 实时时钟(RTC)驱动【转】
    RTC系统【转】
    IRQ和FIQ中断的区别【转】
    NAND Flash【转】
    NandFlash详述【转】
    展讯NAND Flash高级教程【转】
  • 原文地址:https://www.cnblogs.com/tyche116/p/8580992.html
Copyright © 2011-2022 走看看