Strategy.h
#pragma once
#include <iostream>
enum CashSuper_EM
{
CASH_NORMAL = 0,
CASH_REBATE = 1,
};
#define SAFE_DELETE(p) \
if(p)\
{\
delete p; \
p = nullptr;\
}\
// 收費系統,基類
class CashSuper
{
public:
virtual double AcceptCash(double money) = 0;
};
// 正常收費
class CashNormal : public CashSuper
{
public:
double AcceptCash(double money)
{
return money;
}
};
// 打折收費
class CashRebate : public CashSuper
{
public:
CashRebate(double moneyRebate)
{
this->moneyRebate = moneyRebate;
}
double AcceptCash(double money)
{
return money* moneyRebate;
}
private:
double moneyRebate; // 折扣
};
// 環境類CashContext
class CashContext
{
public:
//1. 客戶端判斷哪個策略,然後傳遞CashSuper
CashContext(CashSuper* cashSuper)
{
this->cs = cashSuper;
}
//2. 客戶端判斷轉移到CashContext
CashContext(CashSuper_EM ce)
{
switch (ce)
{
case CASH_NORMAL:
this->cs = new CashNormal();
break;
case CASH_REBATE:
this->cs = new CashRebate(0.8);
break;
default:
this->cs = new CashNormal();
break;
}
}
~CashContext()
{
std::cout << "SAFE_DELETE" << std::endl;
SAFE_DELETE(this->cs);
}
double GetResult(double money)
{
if (cs != nullptr)
{
return cs->AcceptCash(money);
}
return money;
}
private:
CashSuper* cs;// 改用智能指針
};
main.cpp
#include "Strategy.h"
#include <iostream>
using namespace std;
int main()
{
CashSuper_EM cashSuperStr[2] = { CASH_NORMAL,CASH_REBATE };
double money[2] = { 100,100 };
for (int i = 0; i < 2; ++i)
{
CashSuper * cashSuper = nullptr;
CashContext* cashContext = nullptr;
//1. 客戶端判斷哪個策略,然後傳遞CashSuper
switch (cashSuperStr[i])
{
case CASH_NORMAL:
cashSuper = new CashNormal();
cashContext = new CashContext(cashSuper);
break;
case CASH_REBATE:
cashSuper = new CashRebate(0.8);
cashContext = new CashContext(cashSuper);
break;
}
std::cout << cashContext->GetResult(money[i]) << std::endl;
SAFE_DELETE(cashContext)
}
//2. 客戶端判斷轉移到CashContext
for (int i = 0; i < 2; ++i)
{
CashContext* cashContext = new CashContext(cashSuperStr[i]);
std::cout << cashContext->GetResult(money[i]) << std::endl;
SAFE_DELETE(cashContext)
}
return 0;
}