Context.h
#pragma once
#include <iostream>
using namespace std;
class Context1
{
public:
Context1(){};//类的成员函数没有实现就调用,提示错误无法解析外部符号成员
Context1(int money, int cheng) :m_money(money), m_cheng(cheng){}
float getMoney()const{ return m_money; }
float getCheng()const { return m_cheng; }
protected:
private:
float m_money = 100;
float m_cheng = 5;
};
TaxStrategy.h
#pragma once
#include <iostream>
#include "context.h"
using namespace std;
typedef enum{
TYPE_CH_TAX = 0,
TYPE_US_TAX ,
//TYPE_ERROR
}eType;
class TaxStrategy{
public:
TaxStrategy(){}
virtual double Calculate(const Context1 &context) = 0;
virtual ~TaxStrategy(){}
};
class CNTax :public TaxStrategy
{
public:
virtual double Calculate(const Context1 &context)//int getMoney()const{ return m_money; } add const at the last of function that we can use the getMoney
{
double sum = context.getMoney() *context.getCheng();// double int?
cout << "This is Chinese." << endl;
return sum;
}
virtual ~CNTax(){};
};
class USTax :public TaxStrategy
{
public:
virtual double Calculate(const Context1 &context)
{
double sum = context.getMoney() + context.getCheng();
cout << "This is Usa!" << endl;
return sum;
}
virtual ~USTax(){};//虚析构函数没加{}导致没实现,造成产生无法解析外部符号
};
class StrategyFactory
{
public:
StrategyFactory(){}
~StrategyFactory(){}
TaxStrategy* newStrategy(eType type){
if (TYPE_CH_TAX == type)
{
return new CNTax();//在同类中可调用其他类
}
else if (TYPE_US_TAX == type){
return new USTax();
}
else{
cout << "Wrong" << endl;
}
}
};
MainCpp
```cpp
#pragma once
#include "context.h"
#include "SalesOrder.h"
#include "TaxStrategy.h"
#include "StrategyFactory.h"
void show();
int main()
{
show();
system("PAUSE");
return 0;
}
void show()
{
Context1 context;
eType type;
StrategyFactory *pFac = new StrategyFactory();
int i;
cout << "Please input the way:\n" << "1.CN 2.US" << endl;
cin >> i;
TaxStrategy *tax = pFac->newStrategy(type=(eType)(i-1));
cout<<tax->Calculate(context)<<endl;
//delete tax;//删除枚举中的new
delete pFac;
}
简单工厂与策略模式:
https://blog.csdn.net/zd_shu/article/details/105501595
转载请注明原文地址:https://ipadbbs.8miu.com/read-55717.html