策略模式是将一些操作封装起来,使得他们不受具体使用他们的对象的影响,简单的理解起来可以是封装了一些算法,类似于stl里面的查找等算法;这些算法功能一样,对外接口一样
以下是个简单的示例:
class IMember {
public:
virtual double discount() = 0;
};
class normal_member : public IMember {
public:
double discount() {
std::cout << "normal member: 0.9, ";
return 0.9; }
};
class vip_member : public IMember {
public:
double discount() {
std::cout << "vip member: 0.7, ";
return 0.7; }
};
class v_vip_member : public IMember {
public:
double discount() {
std::cout << "v_vip member: 0.5, ";
return 0.5; }
};
class custom {
public:
custom(std::shared_ptr<IMember> sp) : sp_type_(sp){}
double pay(double price) {
if (sp_type_) {
price *= sp_type_->discount();
}
std::cout << "will pay " << price << std::endl;
return price;
}
private:
std::shared_ptr<IMember> sp_type_;
};
int main() {
{
std::shared_ptr<custom> sp_custom1 = std::make_shared<custom>(std::make_shared<vip_member>());
std::shared_ptr<custom> sp_custom2 = std::make_shared<custom>(std::make_shared<v_vip_member>());
std::shared_ptr<custom> sp_custom3 = std::make_shared<custom>(std::make_shared<normal_member>());
//三位用户都买了价值200元的商品
sp_custom1->pay(200);
sp_custom2->pay(200);
sp_custom3->pay(200);
}
}