定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
分离算法,选择实现
策略算法是相同行为的不同实现




//示例1
#include
#include
#include
using namespace std;
//高层策略接口
class Strategy
{
public:
virtual double CalcPrice(double goodsPrice){return 0;}
};
//具体策略
//普通客户策略
class NormalCustomerStrategy : public Strategy
{
public:
double CalcPrice(double goodsPrice) override
{
//普通客户没有折扣
std::cout<<"普通客户没有折扣"<CalcPrice(goodsPrice);
}
return 0;
}
private:
std::unique_ptr pStrategy {nullptr};
};
int main()
{
{
Price price(new NormalCustomerStrategy);
double goodsPrice = price.Quote(100);
std::cout<<"普通客户最终价:"< //示例2
#include
#include
#include
using namespace std;
//策略模式扩展方式
//1.扩展上下文:通过继承上下文方式,然后在子类中添加相关数据
//2.扩展策略算法:在具体策略算法中添加相关数据
//高层策略接口
class PayStrategy
{
public:
//virtual void Pay(PayContext* pPayContext){} //c++ 没有反射 不能直接传入context 然后获取上下文相关数据 适用于扩展方式1
virtual void Pay(const std::string& user, double money){}
};
//具体策略
//人民币现金支付
class RMBCashStrategy : public PayStrategy
{
public:
void Pay(const std::string& user, double money) override
{
std::cout<Pay(this->user, this->money);
}
}
private:
std::unique_ptr pPayStrategy {nullptr};
};
int main()
{
{
PayContext* payContext = new PayContext("张三", 100.0, new RMBCashStrategy());
payContext->PayNow();
}
{
PayContext* payContext = new PayContext("petter", 200.0, new DollarCashStrategy());
payContext->PayNow();
}
{
PayContext* payContext = new PayContext("李四", 300.0, new RMBAccountStrategy("123456789"));
payContext->PayNow();
}
return 0;
}