zoukankan      html  css  js  c++  java
  • 设计模式2——策略模式

    工厂模式是针对不同的类型创建不同的对象,当所需要的对象没有变,而只是对它们进行的操作和算法不同时,可使用策略模式。

    策略模式创建不同的算法类,并返回一个基类算法对象的指针,并对它进行相关的计算或操作。

    实例代码

    Strategy.h内容

     1 #ifndef Strategy_H_H
     2 #define Strategy_H_H
     3 
     4 #include <iostream>
     5 using namespace std;
     6 
     7 class Oper
     8 {
     9 public:
    10     Oper() {}
    11     virtual int getResult(int a, int b) = 0;
    12     virtual ~ Oper() {}
    13 };
    14 
    15 class OperAdd : public Oper
    16 {
    17 public:
    18     virtual int getResult(int a, int b) { return a+b; }
    19 };
    20 
    21 class OperSub : public Oper
    22 {
    23 public:
    24     virtual int getResult(int a, int b) { return a-b; }
    25 };
    26 
    27 class Strategy
    28 {
    29 public:
    30     Strategy(int a0, int b0) : a(a0), b(b0), oper(NULL) {}
    31     int getResult(){
    32         return oper->getResult(a, b);
    33     }
    34     void setOper(Oper *oper0){
    35         oper = oper0;
    36     }
    37 private:
    38     int a, b;
    39     Oper *oper;
    40 };
    41 
    42 void StrategyTest()
    43 {
    44     Strategy *strategy = new Strategy(4, 3);
    45     strategy->setOper( new OperAdd() );
    46     cout << strategy->getResult() << endl;
    47     strategy->setOper( new OperSub() );
    48     cout << strategy->getResult() << endl;
    49     delete strategy;
    50 }
    51 
    52 #endif

    运行结果显而易见。

    当然这里并没有考虑内存泄露等问题,使用时需要注意。若需要对其进行优化,可加入引用计数、智能指针等机制。

  • 相关阅读:
    MySQL 报错记录
    Python连接MySQL
    Linux-mail设置
    样式学习--参照Oracle写法
    Shell的for和select
    Shell 定时发送邮件检查网站脚本/邮件正文
    Linux之 AWK SED
    MySQL excel导入
    《iOS三问》 -- 从动画系统的实现谈iOS核心动画

  • 原文地址:https://www.cnblogs.com/MiniHouse/p/3974498.html
Copyright © 2011-2022 走看看