作用:
定義一系列的算法,把它們一個個封裝起來, 並且使它們可相互替換.本模式使得算法可獨立於使用它的客戶而變化.
解析:
簡而言之一句話,Strategy模式是對算法的封裝.處理一個問題的時候可能有多種算法,這些算法的接口(輸入參數,輸出參數等)都是一致的,那麼可以考慮采用Strategy模式對這些算法進行封裝,在基類中定義一個函數接口就可以了.
實現:
1)Strategy.h
/**//********************************************************************
created: 2006/08/06
filename: Strategy.h
author: 李創
http://www.cppblog.com/converse/
purpose: Strategy模式的演示代碼
*********************************************************************/
#ifndef STRATEGY_H
#define STRATEGY_H
class Strategy;
class Context
{
public:
Context(Strategy *pStrategy);
~Context();
void ContextInterface();
private:
Strategy* m_pStrategy;
};
class Strategy
{
public:
virtual ~Strategy(){}
virtual void AlgorithmInterface() = 0;
};
class ConcreateStrategyA
: public Strategy
{
public:
virtual ~ConcreateStrategyA(){}
virtual void AlgorithmInterface();
};
#endif
2)Strategy.cpp
/**//********************************************************************
created: 2006/08/06
filename: Strategy.cpp
author: 李創
http://www.cppblog.com/converse/
purpose: Strategy模式的演示代碼
*********************************************************************/
#include <iostream>
#include "Strategy.h"
Context::Context(Strategy *pStrategy)
: m_pStrategy(pStrategy)
{
}
Context::~Context()
{
delete m_pStrategy;
m_pStrategy = NULL;
}
void Context::ContextInterface()
{
if (NULL != m_pStrategy)
{
m_pStrategy->AlgorithmInterface();
}
}
void ConcreateStrategyA::AlgorithmInterface()
{
std::cout << "AlgorithmInterface Implemented by ConcreateStrategyA\n";
}
3)Main.cpp
/**//********************************************************************
created: 2006/08/06
filename: Main.cpp
author: 李創
http://www.cppblog.com/converse/
purpose: Strategy模式的測試代碼
*********************************************************************/
#include "Strategy.h"
int main()
{
Strategy* pStrategy = new ConcreateStrategyA();
Context* pContext = new Context(pStrategy);
pContext->ContextInterface();
delete pContext;
return 0;
}