/*shop.h文件*/ #ifndef _SHOP_ #define _SHOP_ #include<iostream> #include<string> //现金收费抽象类 class Cashsuper { public: virtual double acceptcash(double money); }; //正常收费子类 class cashnormal:public Cashsuper { public: virtual double acceptcash(double money); }; //打折收费子类 class cashrebate:public Cashsuper { public: cashrebate():moneyrebate(0.1){} virtual double acceptcash(double money); void calcute_rebate(std::string moneystring); private: double moneyrebate;//打折率 }; //返利收费子类 class cashreturn:public Cashsuper { public: void MoneyReturn(std::string moneycondition_str,std::string moneyreturn_str); virtual double acceptcash(double money); private: double moneycondition;//返利条件(如满300) double moneyreturn;//返利值(返100) }; //用一个算法类来配置,维护一个算法对象的引用 class cashcontxt { public: cashcontxt(Cashsuper* cs){ this->cas=cs; } double getresult(double money); private: Cashsuper* cas; }; #endif
/*shop,cpp文件*/ #include<iostream> #include"shop.h" using namespace std; //现金收费的抽象类(函数定义) double Cashsuper::acceptcash(double money) { return money; } //正常收费的子类(函数定义) double cashnormal::acceptcash(double money) { return money; } //打折收费的子类(函数定义) void cashrebate::calcute_rebate(std::string moneystring) { if(moneystring=="打八折") moneyrebate=0.8; else if(moneystring=="打九折") moneyrebate=0.9; } double cashrebate::acceptcash(double money) { return money*moneyrebate; } //返利收费的子类(函数定义) void cashreturn::MoneyReturn(std::string moneycondition_str,std::string moneyreturn_str) { if(moneycondition_str=="满100") moneycondition=100; if(moneycondition_str=="满200") moneycondition=200; if(moneycondition_str=="满300") moneycondition=300; if(moneyreturn_str=="返10") moneyreturn=10; if(moneyreturn_str=="返50") moneyreturn=50; if(moneyreturn_str=="返100") moneyreturn=100; } double cashreturn::acceptcash(double money) { double result=money; if(result>=moneycondition) result=money-moneyreturn; return result; } double cashcontxt::getresult(double money) { return cas->acceptcash(money); }
/*main.cpp文件*/ #include "shop.h" #include<iostream> using namespace std; int main() { /* string type="打八折"; cashrebate *cx; cx=new cashrebate; cx->calcute_rebate(type); */ string type="满300返100"; cashreturn *cx; cx=new cashreturn; cx->MoneyReturn("满300","返100"); cashcontxt *cs; cs=new cashcontxt(cx); cout<<cs->getresult(1000)<<endl; system("pause"); return 0; }
时间: 2024-10-16 22:35:00