通过对计算器的算法实现抽象,封装,继承,但通过调用积累获取结果时不知道去实例化哪个算法,这里引入了简单的工厂模式,通过运算符的不同去实例化不同算法类,然后去设置值进行运算,代码如下:
// SimpleFactory.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <Windows.h>
class IAlgorithm
{
public:
IAlgorithm():m_a(0),m_b(0){};
virtual double GetResutl() = 0;
void setA(double a){m_a = a;};
void setB(double b){m_b = b;};
double getA(){return m_a;};
double getB(){return m_b;};
private:
double m_a;
double m_b;
};
class CAddition : public IAlgorithm
{
public:
virtual double GetResutl()
{
return getA() + getB();
};
};
class CSubtraction :public IAlgorithm
{
public:
virtual double GetResutl()
{
return getA() - getB();
};
};
class CMultiplication : public IAlgorithm
{
public:
virtual double GetResutl()
{
return getA() * getB();
};
};
class CDivision : public IAlgorithm
{
public:
virtual double GetResutl()
{
return getA() / getB();
};
};
class CSimpleFactory
{
public:
static IAlgorithm *createOperate(char ch)
{
IAlgorithm *pAlgo;
switch (ch)
{
case '+':
pAlgo = new CAddition();
break;
case '-':
pAlgo = new CSubtraction();
break;
case '*':
pAlgo = new CMultiplication();
break;
case '/':
pAlgo = new CAddition();
break;
}
return pAlgo;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
IAlgorithm *pAlgorithm = CSimpleFactory::createOperate('+');
pAlgorithm->setA(10);
pAlgorithm->setB(20);
double val = pAlgorithm->GetResutl();
getchar();
return 0;
}