简单工厂模式
实现整数四则运算 (1) 基本实现 (2) 健壮实现 (3) 工厂模式
#pragma once
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
//(1)基本实现
void BasicFun() {
int nNumberFirst, nNumberSecond;
char cSymbol;
cin >> nNumberFirst;
cin >> nNumberSecond;
cin >> cSymbol;
if (cSymbol == '+') cout << nNumberFirst + nNumberSecond;
if (cSymbol == '-') cout << nNumberFirst - nNumberSecond;
if (cSymbol == '*')cout << nNumberFirst * nNumberSecond;
if (cSymbol == '/')cout << nNumberFirst / nNumberSecond;
getchar();
return ;
}
//(2)规范和健壮性实现
void StandardAndRobustFun() {
int nNumberFirst, nNumberSecond;
string strSymbol="";
try {
cin >> nNumberFirst;
cin >> nNumberSecond;
cin >> strSymbol;
if (nNumberSecond == 0 && strSymbol[0] == '/') {
cout << "error:The dividend cannot be zero ";
return;
}
switch (strSymbol[0]) {
case '+': cout << nNumberFirst + nNumberSecond << endl; break;
case '-': cout << nNumberFirst - nNumberSecond << endl; break;
case '*': cout << nNumberFirst * nNumberSecond << endl; break;
case '/': cout << nNumberFirst / nNumberSecond << endl; break;
default:cout << "Input Format Error" << endl; break;
}
}
catch (void *pErrorKey) {
cout << "Unknow Error" << endl;
}
return;
}
//(3)简单工厂模式
class COperationClass {
public:
virtual bool GetValue(const int &nNumberFirst, const int &nNumberSecond, int &nNumberAns) = 0;
};
class CAddition :public COperationClass {
public:
bool GetValue(const int &nNumberFirst, const int &nNumberSecond, int &nNumberAns) {
nNumberAns = nNumberFirst + nNumberSecond;
return true;
}
};
class Csubtraction :public COperationClass {
public:
bool GetValue(const int &nNumberFirst, const int &nNumberSecond, int &nNumberAns) {
nNumberAns = nNumberFirst - nNumberSecond;
return true;
}
};
class Cmultiplication :public COperationClass {
public:
bool GetValue(const int &nNumberFirst, const int &nNumberSecond, int &nNumberAns) {
nNumberAns = nNumberFirst * nNumberSecond;
return true;
}
};
class Cdivision :public COperationClass {
public:
bool GetValue(const int &nNumberFirst, const int &nNumberSecond, int &nNumberAns) {
if (nNumberSecond == 0) {
return 0;
}
nNumberAns = nNumberFirst / nNumberSecond;
return true;
}
};
class CFactory {
public:
bool GetAlgorithm(const string &strSymbol, COperationClass * &pAlgorithm) {
pAlgorithm = NULL;
switch (strSymbol[0]) {
case '+': pAlgorithm = new CAddition(); break;
case '-': pAlgorithm = new Csubtraction(); break;
case '*': pAlgorithm = new Cmultiplication(); break;
case '/': pAlgorithm = new Cdivision(); break;
default: return false;
}
return pAlgorithm != NULL;
}
};
int main()
{
system("color 0b");
//BasicFun();
//StandardAndRobustFun();
CFactory CFactorTest;
COperationClass * pOperationNow = NULL;
if (CFactorTest.GetAlgorithm("+", pOperationNow)) {
int nComputerResult = 0;
pOperationNow->GetValue(1, 2, nComputerResult);
cout << nComputerResult << endl;
delete(pOperationNow);
}
else {
cout << "error" << endl;
}
getchar();
return 0;
}