#include <iostream>
using namespace std;
class Data
{
public:
Data() {}
Data(const double& dNumberOne, const double& dNumberTwo) : m_dNumberOne(dNumberOne), m_dNumberTwo(dNumberTwo) {}
virtual const double getResult() { return 0; }
void setNumber(const double& dNumberOne, const double& dNumberTwo)
{
m_dNumberOne = dNumberOne;
m_dNumberTwo = dNumberTwo;
}
protected:
double m_dNumberOne = 0;
double m_dNumberTwo = 0;
};
class DataAdd : public Data
{
public:
virtual const double getResult() override { return (m_dNumberOne + m_dNumberTwo); }
};
class DataFactory
{
public:
virtual Data* createDataFactory() = 0;
};
class DataAddFactory : public DataFactory
{
public:
virtual Data* createDataFactory() override { return (new DataAdd()); }
};
int main()
{
DataFactory* pobjDataFactory = new DataAddFactory();
Data* pobjData = pobjDataFactory->createDataFactory();
pobjData->setNumber(1, 2);
cout << pobjData->getResult() << endl;
return 0;
}
总结:工厂模式遵循开放封闭原则,把创建操作类延迟到子类进行,只是需要客户端进行判断需要做什么操作