C++策略模式

Strategy

策略

定义一系列算法,把它们一个个封装起来,并且使它们可以相互替换(变化)。该模式使得算法可以独立于使用它的客户程序(稳定)而变化(扩展、子类化)。

解决什么问题

在软件构建过程中,某些对象使用的算法可能多种多样,经常改变,如果将这些算法都编码到对象中,会使得对象变得异常复杂,而且有时候支持不使用的算法也是一个性能负担。

如何在运行时根据需求更透明的更改对象的算法?

将算法与对象本身解耦,从而避免上述问题?

要点总结

  1. Strategy及其子类为组件提供了一系列可重用的算法,从而使得类型在运行时方便的根据需要在各个算法之间切换
  2. Strategy提供了判断语句外的另一种选择
  3. 如果Strategy对象没有实例变量,那么各个上下文可以共享同一个Strategy对象,从而节省开销

没有使用策略模式:

// 结构化
// 为了区分每一种税收,必须为每一种税收分别做计算方法。

enum TaxBase { // 变化
    CN_Tax,
    US_Tax,
    DE_Tax,
    FR_Tax  // 增加需求
};

class SalesOrder {
public:
// 这些方法,全部在类里面,虽然有枚举,可以跳过其他的方法,但这些方法的增删改都不方便,而且也会使得这个类很庞大
    // 稳定
    double CalculateTax() {
        // ...
  
        if (tax == CN_Tax) {
            // ...
        }
        else if (tax == US_Tax) {
  
        }
        else if (tax == DE_Tax) {
  
        }
        else if (tax == FR_Tax) { // 增加 应该对扩展开放,对修改封闭
  
        }
        //...
    }
  
private:
    TaxBase tax;
};

使用策略模式:

// Strategy
class TaxStrategy {
public:
    virtual double Calculate(const Context& context)=0;
    virtual ~TaxStrategy(){}// 基类最好都实现一个虚的析构函数
};

// 变化
// 把每一种税收计算方法,都封装成一个类,这个类不能实例化,但却有重写的虚函数
// 这样,如果是增加或者减少方法,只需要增加或减少相应的类,而且,根据类不同,其他类的代码不会冗余进来

class CNTax : public TaxStratygy {
public:
    virtual double Calculate(const Context& context) {
        // ...
    }
};

class USTax : public TaxStratygy {
public:
    virtual double Calculate(const Context& context) {
        // ...
    }
};

class DETax : public TaxStratygy {
public:
    virtual double Calculate(const Context& context) {
        // ...
    }
};

// 增加
class FRTax : public TaxStratygy {
public:
    virtual double Calculate(const Context& context) {
        // ...
    }
};

// 稳定
class SalesOrder {
public:
    SalesOrder(StrategyFactory* strategyFactory) {
        this->strategy = strategyFactory->NewStrategy();
    }
  
    ~SalesOrder() {
        delete this->strategy;
    }
  
    double Calculate() {
        // ...
        Context context();
  	// 这个时候调用的就是实际的税收计算方法类里面的方法
        double val = strategy->Calculate(contex);
  
        // ...
    }
  
private:
    TaxStrategy* strategy;
};

C++中的策略模式是一种行为型设计模式,它允许在运行时选择算法的不同实现。该模式定义了一组算法,将它们各自封装起来,并使它们可以互换。 在C++中,可以使用函数指针、函数对象或Lambda表达式来实现策略模式。以下是一个简单的示例: ```c++ #include <iostream> class SortingStrategy { public: virtual void sort(int* arr, int n) = 0; }; class BubbleSort : public SortingStrategy { public: void sort(int* arr, int n) { // Bubble sort implementation std::cout << "Sorting using bubble sort." << std::endl; } }; class QuickSort : public SortingStrategy { public: void sort(int* arr, int n) { // Quick sort implementation std::cout << "Sorting using quick sort." << std::endl; } }; class Sorter { private: SortingStrategy* strategy; public: void setSortingStrategy(SortingStrategy* newStrategy) { strategy = newStrategy; } void sort(int* arr, int n) { strategy->sort(arr, n); } }; int main() { int arr[] = {5, 2, 9, 3, 6}; int n = sizeof(arr) / sizeof(arr[0]); Sorter sorter; BubbleSort bubbleSort; sorter.setSortingStrategy(&bubbleSort); sorter.sort(arr, n); QuickSort quickSort; sorter.setSortingStrategy(&quickSort); sorter.sort(arr, n); return 0; } ``` 在上面的示例中,SortingStrategy是抽象策略类,BubbleSort和QuickSort是具体策略类。Sorter是使用策略模式的上下文类,它可以使用setSortingStrategy方法设置当前使用的SortingStrategy实现,并在sort方法中使用该实现对输入数组进行排序。 运行上面的代码将输出: ``` Sorting using bubble sort. Sorting using quick sort. ``` 这表明程序成功地使用了策略模式来选择不同的排序算法实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

橙子砰砰枪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值