策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。从这些类中抽象出公共接口。策略模式让算法独立于使用它的客户而独立变化。
//图书折扣策略的抽象类 class CBookStrategy { public: virtual double GetDiscount()=0; CBookStrategy() { } }; //无折扣 class CNonDiscount: public CBookStrategy { private: int m_BookCount; double m_BookPrice; public: CNonDiscount(int BookCount,double BookPrice) { m_BookCount = BookCount; m_BookPrice = BookPrice; } virtual double GetDiscount() { return m_BookCount*m_BookPrice; } }; //按百分比折扣 class CPerDiscount : public CBookStrategy { private: int m_BookCount; double m_BookPrice; double m_Percent; public: double GetPercent() { return m_Percent; } void SetPercent(double Percent) { m_Percent = Percent; } CPerDiscount(int BookCount,double BookPrice,double Percent) { m_BookCount = BookCount; m_BookPrice = BookPrice; m_Percent = Percent; } virtual double GetDiscount() { return m_BookCount*m_BookPrice*m_Percent; } }; //按具体价格折扣 class CPriceDiscount: public CBookStrategy { private: int m_BookCount; double m_BookPrice; double m_DiscountPrice; public: double GetDiscountPrice() { return m_DiscountPrice; } void SetPercent(double Price) { m_DiscountPrice = Price; } virtual double GetDiscount() { return m_BookCount*m_DiscountPrice; } CPriceDiscount(int BookCount,double BookPrice,double DiscountPrice) { m_BookCount = BookCount; m_BookPrice = BookPrice; m_DiscountPrice = DiscountPrice; } }; int main(int argc, char* argv[]) { CBookStrategy* pStrategy; //无折扣 pStrategy = new CNonDiscount(2,35); cout << pStrategy->GetDiscount() << '\n'; delete pStrategy; //百分比折扣 pStrategy = new CPerDiscount(2,35,0.85); cout << pStrategy->GetDiscount()<< '\n'; delete pStrategy; //具体价格折扣 pStrategy = new CPriceDiscount(2,35,33); cout << pStrategy->GetDiscount() << '\n'; delete pStrategy; return 0; }