策略模式
同一个物品,有不同策略的情况。将算数封装成策略,根据实际情况调用策略。
下面是英雄选用不同战斗方式的策略。代码如xia :
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 4 using namespace std; 5 6 7 //抽象的策略(抽象的武器) 8 class AbstractStrategy 9 { 10 public: 11 //纯虚函数, 使用具体武器的策略, 12 virtual void useWeapon() = 0; 13 }; 14 15 class KnifeStrategy :public AbstractStrategy 16 { 17 public: 18 virtual void useWeapon() { 19 cout << "使用匕首,进行近战攻击" << endl; 20 } 21 }; 22 23 class AkStrategy :public AbstractStrategy 24 { 25 public: 26 virtual void useWeapon() { 27 cout << "使用ak 进行远程攻击" << endl; 28 } 29 }; 30 31 32 class Hero 33 { 34 public: 35 Hero() 36 { 37 strategy = NULL; 38 } 39 40 void setStrategy(AbstractStrategy *strategy) 41 { 42 this->strategy = strategy; 43 } 44 45 //攻击方法 46 void fight() { 47 cout << "英雄开始战斗了" << endl; 48 this->strategy->useWeapon(); 49 } 50 51 private: 52 //拥有一个 使用攻击策略的抽象成员 53 AbstractStrategy *strategy; 54 }; 55 56 int main(void) 57 { 58 AbstractStrategy *knife = new KnifeStrategy; 59 AbstractStrategy *ak47 = new AkStrategy; 60 61 Hero *hero = new Hero; 62 63 cout << "远程兵来了, 更换远程攻击" << endl; 64 hero->setStrategy(ak47); 65 hero->fight(); 66 67 cout << "近战兵 来了, 更换近战的攻击" << endl; 68 hero->setStrategy(knife); 69 hero->fight(); 70 71 72 73 return 0; 74 }
下面是一个商品上午和下午不同的营销策略。代码如下
1 #define _CRT_SECURE_NO_WARNINGS 2 #include <iostream> 3 4 using namespace std; 5 6 //销售策略 7 class AbstractStrategy 8 { 9 public: 10 //商品具体的销售策略计算方式 11 virtual double getPrice(double price) = 0; 12 }; 13 14 //策略A 商品打八折 15 class StrategyA :public AbstractStrategy 16 { 17 public: 18 virtual double getPrice(double price) { 19 return price*0.8; 20 } 21 }; 22 23 //策略B 如果商品超过200, 减100 24 class StrategyB :public AbstractStrategy 25 { 26 public: 27 virtual double getPrice(double price) 28 { 29 if (price > 200) { 30 price = price - 100; 31 } 32 33 return price; 34 } 35 }; 36 37 38 //商品 39 class Item 40 { 41 public: 42 Item(string name, double price) 43 { 44 this->name = name; 45 this->price = price; 46 } 47 48 //提供一个可以更换策略的方法 49 void setStrategy(AbstractStrategy *strategy) 50 { 51 this->strategy = strategy; 52 } 53 54 //最终获得商品的价格的方法 55 double SellPrice() 56 { 57 return this->strategy->getPrice(this->price); 58 } 59 private: 60 string name; 61 double price;//商品的价格 62 //销售的策略 63 AbstractStrategy *strategy; 64 }; 65 66 67 int main(void) 68 { 69 Item it("nike鞋", 201); 70 AbstractStrategy *sA = new StrategyA; 71 AbstractStrategy *sB = new StrategyB; 72 73 cout << "上午 商场执行 销售策略A 全程八折" << endl; 74 it.setStrategy(sA); //让商品设置A销售策略 75 cout << "nike鞋应该卖" << it.SellPrice() << endl; 76 77 cout << "-----" << endl; 78 cout << "下午商场执行 销售策略B, 全场 超200减100" << endl; 79 it.setStrategy(sB); 80 cout << "nike鞋应该卖" << it.SellPrice() << endl; 81 82 return 0; 83 }