意圖:
定義一系列的演算法,把它們一個個封裝起來,並且使它們可相互替換。本模式使得演算法可獨立於使用它的客戶而變化。
適用環境:
1) 許多相關的類僅僅是行為有異。“策略”提供了一種用多個行為中的一個行為來配置一個類的方法。
2) 需要使用一個演算法的不同變體。例如,你可能會定義一些反映不同的空間/時間權衡的演算法。當這些變體實現為一個演算法的類層次時,可以使用原則模式。
3) 演算法使用客戶不應該知道的資料。可使用原則模式以避免暴露複雜的、與演算法相關的資料結構。
4) 一個類定義了多種行為, 並且這些行為在這個類的操作中以多個條件陳述式的形式出現。將相關的條件分支移入它們各自的Strategy類中以代替這些條件陳述式。
結構:
實現:
Stratey.h檔案
#pragma
once
class
stratey
{
public:
stratey(void);
virtual ~stratey(void);
virtual
void AlgrithmInterface()=0;
};
class
ConcreteStrategyA:public
stratey
{
public:
ConcreteStrategyA();
~ConcreteStrategyA();
void
AlgrithmInterface();
};
class
ConcreteStrategyB:public
stratey
{
ConcreteStrategyB();
~ConcreteStrategyB();
void
AlgrithmInterface();
};
Stratey.cpp檔案
#include
"StdAfx.h"
#include
<iostream>
using namespace
std;
#include
"stratey.h"
stratey::stratey(void)
{
}
stratey::~stratey(void)
{
cout<<"~ strategy......."<<endl;
}
void
stratey:: AlgrithmInterface()
{
}
ConcreteStrategyA::ConcreteStrategyA()
{
}
ConcreteStrategyA::~ConcreteStrategyA(void)
{
cout<<"~ ConcretestrategyA......."<<endl;
}
void
ConcreteStrategyA:: AlgrithmInterface()
{
cout<<"using A algrithminterface"<<endl;
}
ConcreteStrategyB::ConcreteStrategyB()
{
}
ConcreteStrategyB::~ConcreteStrategyB(void)
{
cout<<"~ ConcretestrategyB......."<<endl;
}
void
ConcreteStrategyB:: AlgrithmInterface()
{
cout<<"using B algrithminterface"<<endl;
}
Context.h檔案
#pragma
once
#include
"stratey.h"
class
Context
{
public:
Context(stratey *stg);
virtual ~Context(void);
void
DoSomething();
private:
stratey *m_stratey;
};
Context.cpp檔案
#include
"StdAfx.h"
#include
"Content.h"
Context::Context(stratey *stg)
{
m_stratey=stg;
}
Context::~Context(void)
{
if (m_stratey!=NULL)
{
delete m_stratey; //沒有在定義的對象地方釋放記憶體
}
}
void
Context::DoSomething()
{
m_stratey->AlgrithmInterface();
}
主函數:
// strategyPattern.cpp : 定義控制台應用程式的進入點。
//
#include
"stdafx.h"
#include
"stratey.h"
#include
"Content.h"
#include
<iostream>
using namespace
std;
int _tmain(int
argc, _TCHAR*
argv[])
{
stratey *ps;
ps=new
ConcreteStrategyA();
Context *pc=new
Context(ps);
pc->DoSomething();
if (pc!=NULL)
{
delete
pc;
}
return 0;
}
結果: