适用情景: 根据输入条件的不同,创建不同的类的对象.
缺陷:客户端需要了解基类和工厂类.
C++实现:
// coperation.h
#ifndef COPERATION_H
#define COPERATION_H
class COperation
{
public:
COperation();
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult();
};
#endif // COPERATION_H
// coperation.cpp
#include "coperation.h"
COperation::COperation()
{
}
double COperation::GetResult()
{
double dResult = 0;
return dResult;
}
// caddoperation.h
#ifndef CADDOPERATION_H
#define CADDOPERATION_H
#include "coperation.h"
class CAddOperation : public COperation
{
public:
CAddOperation();
virtual double GetResult();
};
#endif // CADDOPERATION_H
// caddoperation.cpp
#include "caddoperation.h"
CAddOperation::CAddOperation()
{
}
double CAddOperation::GetResult()
{
return m_nFirst + m_nSecond;
}
// csuboperation.h
#ifndef CSUBOPERATION_H
#define CSUBOPERATION_H
#include "coperation.h"
class CSubOperation : public COperation
{
public:
CSubOperation();
virtual double GetResult();
};
#endif // CSUBOPERATION_H
// csuboperation.cpp
#include "csuboperation.h"
CSubOperation::CSubOperation()
{
}
double CSubOperation::GetResult()
{
return m_nFirst - m_nSecond;
}
// csimplefactory.h
#ifndef CSIMPLEFACTORY_H
#define CSIMPLEFACTORY_H
#include "coperation.h"
class CSimpleFactory
{
public:
CSimpleFactory();
public:
static COperation * Create(char cOperator);
};
#endif // CSIMPLEFACTORY_H
// csimplefactory.cpp
#include "csimplefactory.h"
#include "caddoperation.h"
#include "csuboperation.h"
CSimpleFactory::CSimpleFactory()
{
}
COperation * CSimpleFactory::Create(char cOperator)
{
COperation * opt;
switch (cOperator) {
case '+':
{
opt = new CAddOperation();
}
break;
case '-':
{
opt = new CSubOperation();
}
break;
default:
opt = nullptr;
break;
}
return opt;
}
客户端:
// main.cpp
#include <iostream>
#include "coperation.h"
#include "csimplefactory.h"
using namespace std;
int main(int argc, char *argv[])
{
COperation * opt = CSimpleFactory::Create('+');
int a, b;
cin >> a;
cin >> b;
opt->m_nFirst = a;
opt->m_nSecond = b;
cout << opt->GetResult() << endl;
return 0;
}