1. 不好的代码
enum TaxBase {
CN_Tax,
US_Tax,
DE_Tax,
FR_Tax
};
class SalesOrder{
TaxBase tax;
public:
double CalculateTax(){
if (tax == CN_Tax){
}
else if (tax == US_Tax){
}
else if (tax == DE_Tax){
}
else if (tax == FR_Tax){
}
}
};
2. 好的代码
class TaxStrategy{
public:
virtual double Calculate(const Context& context)=0;
virtual ~TaxStrategy(){}
};
class CNTax : public TaxStrategy{
public:
virtual double Calculate(const Context& context){
}
};
class USTax : public TaxStrategy{
public:
virtual double Calculate(const Context& context){
}
};
class DETax : public TaxStrategy{
public:
virtual double Calculate(const Context& context){
}
};
class FRTax : public TaxStrategy{
public:
virtual double Calculate(const Context& context){
}
};
class SalesOrder{
private:
TaxStrategy* strategy;
public:
SalesOrder(StrategyFactory* strategyFactory){
this->strategy = strategyFactory->NewStrategy();
}
~SalesOrder(){
delete this->strategy;
}
public double CalculateTax(){
Context context();
double val =
strategy->Calculate(context);
}
};