c++-策略模式


策略模式和上节提到的 模板模式有很多相似之处
模板模式链接

本文用策略模式实现上节模板模式相同的冒泡排序算法
可以发现
模板模式的 变化都下沉到子类, 通过继承实现
策略模式 变化在于组合的对象, 通过组合实现

简单代码实现

#include <iostream>
#include <vector>
#include <string>

using namespace std;


class BubbleSorterInterface {
 public:
    [[nodiscard]] virtual bool compare(int index) const = 0;

    virtual void swap(int) = 0;

    [[nodiscard]] virtual size_t length() const = 0;
};

// 冒泡排序
class BubbleSorter {
 private:
    BubbleSorterInterface* sorter;
 public:
    explicit BubbleSorter(BubbleSorterInterface* bsi) : sorter(bsi) {}

    void setSorterInterface(BubbleSorterInterface* bsi) {
        sorter = bsi;
    }

    virtual void doSort() {
        for (int i = 0; i < sorter->length() - 1; i++) {
            for (int j = 0; j < sorter->length() - i - 1; j++) {
                if (sorter->compare(j)) {
                    sorter->swap(j);
                }
            }
        }
    }

 private:
};

class intBubbleSorterInterface : public BubbleSorterInterface {
 private:
    vector<int> &_data;
 public:
    explicit intBubbleSorterInterface(vector<int> &data) : _data(data) {}

 private:
    [[nodiscard]] bool compare(int index) const override {
        return _data[index] > _data[index + 1];
    }

    void swap(int index) override {
        ::swap(_data[index], _data[index + 1]);
    }

    [[nodiscard]] size_t length() const override {
        return _data.size();
    }
};

class stringBubbleSorterInterface : public BubbleSorterInterface {
 private:
    vector<string> &_data;
 public:
    explicit stringBubbleSorterInterface(vector<string> &data) : _data(data) {}

 private:
    [[nodiscard]] bool compare(int index) const override {
        return _data[index] > _data[index + 1];
    }

    void swap(int index) override {
        ::swap(_data[index], _data[index + 1]);
    }

    [[nodiscard]] size_t length() const override {
        return _data.size();
    }
};

int main(int argc, char **argv) {
    // int 冒泡排序
    vector<int> int_data = {1, 3, 2, 5, 7, 4};

    BubbleSorterInterface* bi = new intBubbleSorterInterface(int_data);
    BubbleSorter bs(bi);
    bs.doSort();
    cout << "int sort answer: ";
    for (auto v : int_data) {
        cout << v << " ";
    }
    cout << endl;

    vector<string> str_data = {"hell world", "I love you", "good bye"};
    BubbleSorterInterface* bis = new stringBubbleSorterInterface(str_data);
    bs.setSorterInterface(bis);
    
    bs.doSort();
    cout << "string sort answer: ";
    for (auto &str : str_data) {
        cout << "[" << str << "] ";
    }
    cout << endl;
}

输出

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值