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

    根据需求的不同 选择不同的策略算法

    之前是保存的各种策略类的指针

    这里直接使用 function  bind 选择对应的算法

    代码

    // 005.cpp: 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <functional>
    #include <iostream>
    
    using namespace std;
    
    
    
    
    int MyAdd(int a, int b) { return a + b; }
    
    class MyMinus {
    public:
        int operator()(int a, int b) {
            return a - b;
        }
    };
    
    class binary_operators {
    public:
        typedef std::function<int(int, int)> FUNC;
        binary_operators(FUNC f,int a, int b) :func_(f),left(a), right(b),result(0) {}
        int GetResult() { return func_(left, right); }
    private:
        std::function<int(int, int)> func_;
        int left;
        int right;
        int result;
    };
    
    int main()
    {
        binary_operators addOperation(std::function<int(int, int)>(MyAdd),1,2);
        binary_operators minusOperation(std::function<int(int, int)>(MyMinus()), 5, 7);
        
        std::cout << "addOperation(1,2) result: " << addOperation.GetResult() << std::endl;
        std::cout << "minusOperation(5,7) result: " << minusOperation.GetResult() << std::endl;
        return 0;
    }
    View Code
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    关于 Profile
    empty
    Vim Editor
    C++ Note
    Android NDK Sample
    Dealing with the ! when you import android project
    File attributes and Authority of Linux
    Java与C的相互调用
    The source code list of Android Git project
    Enable Android progurad in the case of multiple JAR lib
  • 原文地址:https://www.cnblogs.com/itdef/p/7457016.html
Copyright © 2011-2022 走看看