1.策略模式概述
1.1、意圖
定義一系列算法,把他們一個個封裝起來,並且使他們可相互替換。使得算法可獨立於使用它的客戶而變化。
1.2、適用性
- 許多相關的類僅僅是行爲有異。可以用多個行爲中的一個行爲來配置一個類的方法。
- 一個類定義了多種行爲,並且這些行爲在這個類的操作中以多個條件語句的形式出現。將相關的條件分支移入它們各自的Stategy類中代替這些條件語句。
- Context類使用Strategy類實現一個接口完成不同功能。
- ConcreteStrategy重寫AlgorithmInterface()方法實現具體功能。
2.代碼示例
//Strategy類
class CountryStrategy {
public:
CountryStrategy() {}
virtual ~CountryStrategy(){}
virtual void whichContury() = 0;
};
//ConcreteStrategyA
class ChinaCountry : CountryStrategy {
public:
virtual void whichContury() {
std::cout << "中國" << std::endl;
}
};
//ConcreteStrategyB
class AmericaCountry : CountryStrategy {
public:
virtual void whichContury() {
std::cout << "美國" << std::endl;
}
};
//ConcreteStrategyC
class FranceCountry : CountryStrategy {
public:
virtual void whichContury() {
std::cout << "法國" << std::endl;
}
};
//Context類
class CountryRegister {
CountryStrategy *m_countryStrategy;
public:
CountryRegister(CountryStrategy *countryStrategy) {
m_countryStrategy = countryStrategy;//這邊應該使用工廠模式生產
}
void registerCountry() {
m_countryStrategy->whichContury();
}
};
int main()
{
FranceCountry france;
AmericaCountry america;
ChinaCountry china;
CountryRegister country1((CountryStrategy *)&france);
country1.registerCountry();
CountryRegister country2((CountryStrategy *)&america);
country2.registerCountry();
CountryRegister country3((CountryStrategy *)&china);
country3.registerCountry();
system("pause");
return 0;
}
輸出結果: