C++实现设计模式之 —策略与简单工程结合

时间:2023-03-09 18:12:11
C++实现设计模式之 —策略与简单工程结合

策略模式封装算法

 // cash.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string.h>
#include <math.h>
using namespace std;
class CashSuper
{
public:
virtual double accpetCash(double money)= ;
};
class CashNormal:public CashSuper
{
public:
double accpetCash(double money) override
{
return money;
}
};
class CashRebate:public CashSuper
{
public:
CashRebate(double moneyRebate)
{
moneyRebate = moneyRebate;
}
double accpetCash(double money) override
{
return money * moneyRebate;
}
private:
double moneyRebate;
};
class CashReturn:public CashSuper
{
public:
CashReturn(double moneyCondition,double moneyReturn)
{
this->moneyCondition = moneyCondition;
this->moneyReturn = moneyReturn;
}
double accpetCash(double money) override
{
double result = money;
if(money > moneyCondition)
{
result = money - floor(money/moneyCondition)*moneyReturn; }
return result;
}
private:
double moneyCondition;
double moneyReturn;
};
class CashFactory
{
public:
static CashSuper *createCashAccpet(char type)
{
CashSuper *cs;
switch(type)
{
case '':
cs = new CashNormal();
break;
case '':
cs = new CashReturn(,);
break;
case '':
cs = new CashRebate(0.8);
break;
}
return cs;
}
};
class CashContext
{
public:
CashContext(char type)
{
switch(type)
{
case '':
cs = new CashNormal();
break;
case '':
cs = new CashReturn(,);
break;
case '':
cs = new CashRebate(0.8);
break;
}
}
CashSuper *cs;
double GetResult(double money)
{
return cs->accpetCash(money);
}
}; int _tmain(int argc, _TCHAR* argv[])
{
CashContext csuper('');
double result = ;
result = csuper.GetResult();
cout<<result<<endl;
system("pause");
return ;
}