策略模式模式C++實現
阿新 • • 發佈:2018-11-03
策略模式:
當用戶需要選擇不同的演算法或行為時,如果把這些演算法或行為寫在一個類裡,通過判斷來選擇的話,這個類將變得非常複雜並且難以維護。策略模式就是構造一個抽象類,具體的演算法或者行為繼承這個類,讓使用者來選擇。這樣做的好處是,可以隨時增加或者修改行為,即增加、修改演算法或行為的類就可以了。
策略模式和簡單工廠模式的差別:
簡單工廠模式是通過一個抽象類來構造新物件,使用者接觸不到具體物件。
策略模式是通過抽象類來選擇行為或演算法。
UML類圖:
C++程式碼實現:
#include <iostream> #include <string> class CashSuper { public: CashSuper() = default; CashSuper(double d) : Money(d) {} virtual double acceptCash() { return Money; } double Money; }; class CashNormal : public CashSuper { public: CashNormal() = default; CashNormal(double d) : CashSuper(d) {} double acceptCash() override { return Money; } }; class CashDiscount : public CashSuper { public: CashDiscount () = default; CashDiscount(double d) : CashSuper(d) {} double acceptCash() override { return Money * 0.8; } }; class CashReturn : public CashSuper { public: CashReturn() = default; CashReturn(double d) : CashSuper(d) {} double acceptCash() override { int i = Money / 100; return Money - i * 30; } }; class CashContext { public: CashSuper cs; std::string CashName; CashSuper* getCash(std::istream& in) { std::cout << " Enter money and n or d or r!" << std::endl; in >> cs.Money >> CashName; if (CashName == "n") return new CashNormal (cs.Money); if (CashName == " d") return new CashDiscount (cs.Money); if (CashName == "r") return new CashReturn (cs.Money); } void showResults() { CashSuper* cs = getCash(std::cin); std::cout << cs->acceptCash() << std::endl; } }; void main() { CashContext cc; cc.showResults(); }
在策略模式的學習過程中,我覺得它和工廠模式很像,難以區別,可能寫出來的程式碼有誤,還要再查資料把這兩個模式搞清楚。