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

    运行结果显而易见。

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

  • 相关阅读:
    docker tcp配置
    PostgreSQL 数据库备份
    docker 几种磁盘卷挂载方式的区别
    MAT
    OkHttp
    HashMap 在 Java1.7 与 1.8 中的区别
    【zabbix】zabbix 高可用架构的实现
    利用zabbix监控Vmware运行
    logback在SpringBoot下出现no applicable action for [appender], current ElementPath is
    NGUI:HUD Text(头顶伤害漂浮文字)
  • 原文地址:https://www.cnblogs.com/MiniHouse/p/3974498.html
Copyright © 2011-2022 走看看