MST

星途 面试题库

面试题:C++中策略模式的应用场景及实现

请简述C++中策略模式适用于哪些场景,并使用C++代码实现一个简单的策略模式示例,比如实现不同的排序策略。
12.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

策略模式适用场景

  1. 算法多变场景:当一个系统需要在多种算法中进行选择,并且这些算法在运行时可以动态切换。例如,不同的加密算法、不同的图形渲染算法等。
  2. 行为封装场景:将一组相关的行为封装起来,使得它们可以相互替换,并且客户端不需要知道具体的实现细节。比如电商系统中不同的支付策略(支付宝支付、微信支付、银行卡支付等)。
  3. 避免多重条件判断场景:在传统代码中,如果根据不同条件执行不同行为,可能会出现大量的if - elseswitch - case语句,使用策略模式可以避免这种复杂的条件判断结构,使代码更易于维护和扩展。

C++ 代码实现简单策略模式(排序策略)

#include <iostream>
#include <vector>
#include <algorithm>

// 抽象策略类
class SortStrategy {
public:
    virtual void sort(std::vector<int>& data) = 0;
};

// 具体策略类:冒泡排序
class BubbleSort : public SortStrategy {
public:
    void sort(std::vector<int>& data) override {
        int n = data.size();
        for (int i = 0; i < n - 1; ++i) {
            for (int j = 0; j < n - i - 1; ++j) {
                if (data[j] > data[j + 1]) {
                    std::swap(data[j], data[j + 1]);
                }
            }
        }
    }
};

// 具体策略类:快速排序
class QuickSort : public SortStrategy {
private:
    int partition(std::vector<int>& data, int low, int high) {
        int pivot = data[high];
        int i = low - 1;
        for (int j = low; j < high; ++j) {
            if (data[j] <= pivot) {
                ++i;
                std::swap(data[i], data[j]);
            }
        }
        std::swap(data[i + 1], data[high]);
        return i + 1;
    }

    void quickSort(std::vector<int>& data, int low, int high) {
        if (low < high) {
            int pi = partition(data, low, high);
            quickSort(data, low, pi - 1);
            quickSort(data, pi + 1, high);
        }
    }
public:
    void sort(std::vector<int>& data) override {
        quickSort(data, 0, data.size() - 1);
    }
};

// 上下文类
class Sorter {
private:
    SortStrategy* strategy;
public:
    Sorter(SortStrategy* strategy) : strategy(strategy) {}

    void setStrategy(SortStrategy* strategy) {
        this->strategy = strategy;
    }

    void executeSort(std::vector<int>& data) {
        if (strategy) {
            strategy->sort(data);
        }
    }
};

可以通过以下方式调用:

int main() {
    std::vector<int> data = {64, 34, 25, 12, 22, 11, 90};

    // 使用冒泡排序策略
    SortStrategy* bubbleSort = new BubbleSort();
    Sorter sorter(bubbleSort);
    sorter.executeSort(data);
    std::cout << "冒泡排序结果: ";
    for (int num : data) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 切换为快速排序策略
    SortStrategy* quickSort = new QuickSort();
    sorter.setStrategy(quickSort);
    data = {64, 34, 25, 12, 22, 11, 90};
    sorter.executeSort(data);
    std::cout << "快速排序结果: ";
    for (int num : data) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    delete bubbleSort;
    delete quickSort;
    return 0;
}