策略模式
作者:互联网
策略模式
定义一系列算法,把它们一个个封装起来,并且使它们可互相替换(变化)。该模式使得算法可独立于使用它的客户程序(稳定)而变化(扩展,子类化)。
阶段一
enum TaxBase{
CN_TAX,
US_TAX,
DE_TAX,
};
class SalesOrder{
public:
double calculateTax()
{
//...
if(tax_base_==TaxBase::CN_TAX)
{
//...
}
else if(tax_base_==TaxBase::US_TAX)
{
//...
}
else if(tax_base_==TaxBase::DE_TAX)
{
//...
}
//...
}
private:
TaxBase tax_base_;
}
阶段二
class TaxStrategy
{
public:
TaxSalesStrategy(){ }
virtual ~TaxSalesStrategy(){ }
virtual double calculate(Context& context) = 0;
}
class CNTaxStrategy
{
public:
virtual double calculate(Context& context) override
{
//...
}
}
class USTaxStrategy
{
public:
virtual double calculate(Context& context) override
{
//...
}
}
class DETaxStrategy
{
public:
virtual double calculate(Context& context) override
{
//...
}
}
类图
classDiagram class Context{ +ContextInterface() } class Strategy{ +algorithmInterface() } class ConcreteStrategyA{ +algorithmInterface() } class ConcreteStrategyB{ +algorithmInterface() } class ConcreteStrategyC{ +algorithmInterface() } Context o-- Strategy : strategy Strategy <|-- ConcreteStrategyA Strategy <|-- ConcreteStrategyB Strategy <|-- ConcreteStrategyC标签:...,策略,TAX,模式,Strategy,virtual,Context,class 来源: https://www.cnblogs.com/shiguoliang/p/15366832.html