//策略模式
//抽象出算法
//可適應算放的頻繁改動
//問1:和簡單工廠有什麼區別?
//答1:策略模式主要是將算法提煉出來,一個大的context中可以包括多個算法,便於context中算法的的自由配置,
//一次配置,多次使用,維持context的穩定性。
//簡單類工廠模式主要是用於創建一個完整的對象,級別和策略模式不同。
//策略模式中可以包括一個工廠模式的抽象類的對象。
自己畫的圖,囧,將就吧
[cpp]
#include "stdafx.h"
class CashSuper
{
public:
virtual double CalcCash() = 0;
void SetOrginCash(double dOrgCash)
{
m_dOrgCash = dOrgCash;
}
protected:
double m_dOrgCash;
};
class CashReBate : public CashSuper
{
public:
double CalcCash()
{
return m_dOrgCash * 0.85;
}
};
class CashReturn : public CashSuper
{
public:
double CalcCash()
{
if (m_dOrgCash > 300)
{
return m_dOrgCash - 100;
}
else
{
return m_dOrgCash;
}
}
};
class CashContext
{
public:
double GetResult(double dMoney)
{
m_pCashSuper->SetOrginCash(dMoney);
return m_pCashSuper->CalcCash();
}
void SetCashSuper(CashSuper *pCashSuper)
{
m_pCashSuper = pCashSuper;
}
/*void ReleaseCashSuper()
{
if (m_pCashSuper)
{
delete m_pCashSuper;
m_pCashSuper = NULL;
}
}*/
protected:
CashSuper *m_pCashSuper;
};
int _tmain(int argc, _TCHAR* argv[])
{
//現在商場進入打折季節,都使用打折suanfa
CashSuper *pCSuper = new CashReBate;
CashContext CContext;
CContext.SetCashSuper(pCSuper);
//CContext.SetCashSuper(new CashReturn)
//CContext.ReleaseCashSuper();
double dPay = CContext.GetResult(100.0f);
if (pCSuper)
{
delete pCSuper;
pCSuper = NULL;
}
return 0;
}