common.h
/*************************************************************************
> File Name: common.h
> Author: banglang
> Mail: banglang.huang@foxmail.com
> Created Time: Thursday, March 20, 2014 PM01:57:44 CST
************************************************************************/
#ifndef _COMMON_H_
#define _COMMON_H_
#include<iostream>
using namespace std;
#endif /* _COMMON_H_ */
strategy.h
#ifndef _STRATEGY_H_
#define _STRATEGY_H_
#include "common.h"
class cashSuper
{
public:
virtual double acceptMoney(double) = 0;
protected:
double money;
};
class cashNormal : public cashSuper
{
public:
double acceptMoney(double money) {
return money;
}
};
class cashReturn : public cashSuper
{
public:
cashReturn(double _conditioin, double _ret) {
this->cond = _conditioin;
this->ret = _ret;
}
double acceptMoney(double money) {
return ( money - ( ((int)(money / this->cond)) * this->ret) );
}
private:
double cond;
double ret;
};
class cashDiscount : public cashSuper
{
public:
cashDiscount(double _rebate) {
if(_rebate < 0) {
this->rebate = 1;
return;
}
this->rebate = _rebate;
}
double acceptMoney(double money) {
return ( money * this->rebate );
}
private:
double rebate;
};
#endif /* _STRATEGY_H */
context.h
#include "common.h"
#include "strategy.h"
#define ACPT_TYPE_NORMAL 0
#define ACPT_TYPE_RETURN 1
#define ACPT_TYPE_DISCOUNT 2
class CashContext
{
public:
CashContext(int t) {
this->cs = NULL;
switch(t)
{
case ACPT_TYPE_NORMAL:
cs = new cashNormal();
break;
case ACPT_TYPE_RETURN:
cs = new cashReturn(300, 10);
break;
case ACPT_TYPE_DISCOUNT:
cs = new cashDiscount(0.8);
break;
default:
cout<<"ACPT_TYPE Error, set as default:Normal\n";
cs = new cashNormal();
break;
}
}
double acceptCash(double money) {
if(!this->cs) {
cout<"Object Error\n";
return 0;
}
return (this->cs->acceptMoney(money));
}
private:
cashSuper *cs;
};
main.cpp
#include "common.h"
#include "strategy.h"
#include "context.h"
int main(void)
{
CashContext *c1 = NULL;
CashContext *c2 = NULL;
CashContext *c3 = NULL;
double money = 700;
double result = 0;
/*normal*/
c1 = new CashContext(ACPT_TYPE_NORMAL);
result = c1->acceptCash(money);
cout<<"result normal="<<result<<endl;
/*discount*/
c2 = new CashContext(ACPT_TYPE_DISCOUNT);
result = c2->acceptCash(money);
cout<<"result discount="<<result<<endl;
/*return*/
c3 = new CashContext(ACPT_TYPE_RETURN);
result = c3->acceptCash(money);
cout<<"result return="<<result<<endl;
delete(c1);
delete(c2);
delete(c3);
return 0;
}