#include <string>
#include <iostream>
#include <assert.h>
using namespace std;
class SaleStrategy
{
public:
virtual float calculate(float price, int amount) = 0;
};
class RegularSaleStrategy : public SaleStrategy
{
public:
virtual float calculate(float price, int amount)
{
return price * amount;
}
};
class StudentSaleStrategy : public SaleStrategy
{
public:
virtual float calculate(float price, int amount)
{
const float DISCOUNT = 0.5f;
return (1-DISCOUNT) * price * amount;
}
};
class BulkSaleStrategy : public SaleStrategy
{
public:
virtual float calculate(float price, int amount)
{
const float DISCOUNT = 0.3f;
const int BULK_LIMIT = 100;
if (amount >= BULK_LIMIT)
return (1-DISCOUNT) * price * amount;
return price * amount;
}
};
class SaleManager
{
public:
SaleManager(SaleStrategy* pSaleStrategy = NULL) : m_pSaleStrategy(pSaleStrategy) {}
public:
void setStrategy(SaleStrategy* pSaleStrategy)
{
m_pSaleStrategy = pSaleStrategy;
}
float calculateTotal(float price, int amount)
{
assert(m_pSaleStrategy != NULL);
float calResult = m_pSaleStrategy->calculate(price, amount);
cout << "total price is: " << calResult << endl;
return calResult;
}
private:
SaleStrategy* m_pSaleStrategy;
};
int main(int argc, char** argv)
{
SaleStrategy* pSaleStrategy = new RegularSaleStrategy();
SaleStrategy* pStudentSaleStrategy = new StudentSaleStrategy();
SaleStrategy* pBulkSaleStrategy = new BulkSaleStrategy();
SaleManager saleManager(pSaleStrategy);
cout << "Regular Sale Strategy:\n";
saleManager.calculateTotal(2.5f, 100);
saleManager.setStrategy(pStudentSaleStrategy);
cout << "Student Sale Strategy:\n";
saleManager.calculateTotal(2.5f, 100);
saleManager.setStrategy(pBulkSaleStrategy);
cout << "Bulk Sale Strategy:\n";
saleManager.calculateTotal(2.5f, 100);
delete pBulkSaleStrategy;
delete pStudentSaleStrategy;
delete pSaleStrategy;
return 0;
}