设计模式:Strategy(策略)

Posted leocc325

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式:Strategy(策略)相关的知识,希望对你有一定的参考价值。

意图:定义一系列的算法,把他们一个个封装起来,并且使他们可以互相替换,使算法可以独立于使用它的客户变化而变化

暂无理解,以后再回来编辑,先贴代码

TaxStrategy.h

#pragma once
class TaxStrategy
{
    virtual double Calculate() = 0;
    virtual ~TaxStrategy() {};
};
CNTax.h

#pragma once
#include "TaxStrategy.h"
class CNTax :
    public TaxStrategy
{
public:
    virtual double Calculate();
};
DETax.h

#pragma once
#include "TaxStrategy.h"
class DETax :
    public TaxStrategy
{
    virtual double Calculate();
};
USTax.h

#pragma once
#include "TaxStrategy.h"
class USTax :
    public TaxStrategy
{
public:
    virtual double Calculate();
};
SalesOrder.h

#pragma once
#include"TaxStrategy.h"
class SalesOrder
{
    TaxStrategy * strategy;
public:
    SalesOrder(StrategeFactory * factory);//需要一个工厂类,省略
    ~SalesOrder();
    double Calculate();
};
TasStrategy.cpp

#include "TaxStrategy.h"
CNTax.cpp

#include "CNTax.h"

double CNTax::Calculate()
{
    return 111.111;
}
DETax.cpp

#include "DETax.h"

double DETax::Calculate()
{
    return 333.333;
}
USTax.cpp

#include "USTax.h"

double USTax::Calculate()
{
    return 222.222;
}
SalesOrder.cpp

#include "SalesOrder.h"

SalesOrder::SalesOrder(StrategeFactory * factory)
{
    this->strategy = StrategyFactory->newStrategy();
}

SalesOrder::~SalesOrder()
{
    delete this->strategy;
}

double SalesOrder::Calculate()
{
    double val = strategy->Calculate();
    return val;
}
main.cpp

#include <iostream>
#include"SalesOrder.h"
int main()
{
    std::cout << "Hello World!
";
}

未完成.

 

以上是关于设计模式:Strategy(策略)的主要内容,如果未能解决你的问题,请参考以下文章

策略模式(Strategy Pattern)

设计模式之- 策略模式(Strategy Pattern)

设计模式:Strategy(策略)

Java设计模式之策略模式(Strategy)

1.Strategy Pattern(策略模式)

23种设计模式之策略模式(Strategy)