2019-02-26
前面也说了:
在我看来这个简单工厂模式,主要针对方向就可扩展性。
要求是实现一个简单的计算器。
为了隐藏实现细节,将运算细节单独封装,使用了封装特性。
为了代码复, 建造一个运算父类,几个运算子类继承与运算父类,使用继承特性。
为了代码得可扩展性,创建一个工厂类去实例化运算子类的对象,使用了多态特性。
具体代码如下:
#include<iostream>
using namespace std;
class Operation
{
private:
/* data */
public:
Operation(/* args */){
cout << "Operation 构造" << endl;
};
double num_1 ;
double num_2 ;
virtual double GetResult(double num_1,double num_2) = 0;
~Operation()
{
cout << "Operation 析构" << endl;
}
};
class OperationAdd :public Operation
{
private:
/* data */
public:
OperationAdd(/* args */){
cout << "OperationAdd 构造" << endl;
};
double GetResult(double num_1,double num_2){
cout << num_1 << " " << num_2 <<endl;
return (num_1 + num_2);
}
};
class OperationSub : public Operation
{
private:
/* data */
public:
OperationSub(/* args */){
cout << "OperationSub 构造" << endl;
};
double GetResult(double num_1,double num_2){
cout << num_1 << " " << num_2 <<endl;
return (num_1 - num_2);
}
};
class Factory
{
private:
/* data */
public:
Factory(/* args */){
cout << "Factory 构造" << endl;
};
Operation* create_Operat(string operat)
{
//根据传入的运算符不同,实例化不同的运算子类
Operation* oper = NULL;
if("+" == operat)
oper = new OperationAdd();
if("-" == operat)
oper = new OperationSub();
//将子类对象return 出去。
return oper;
}
~Factory(){
cout << "Factory 析构" << endl;
}
};
int main()
{
double num_1 ;
double num_2 ;
string operat;
cout << "请输入第一个数字" << endl;
cin >> num_1 ;
cout << "请输入运算符 " << endl;
cin >> operat;
cout << "请输入第二个数字" << endl;
cin >> num_2 ;
Factory * fa = new Factory();
//实例化一个工厂类的对象,用工厂类的对象的create_Operat方法实例化几个运算子类的对象,
Operation * op = fa->create_Operat(operat);
//父类指针指向子类对象,调用子类实现。
double result = op->GetResult(num_1, num_2);
cout << num_1 << " " << operat << " " << num_2 << " = " << result << endl;
delete fa;
delete op;
return 0;
}
coding 过程中遇到的问题:
Operation.cpp:(.text._ZN7Factory13create_OperatESs[_ZN7Factory13create_OperatESs]+0x41): undefined reference to `OperationAdd::OperationAdd()'
Operation.cpp:(.text._ZN7Factory13create_OperatESs[_ZN7Factory13create_OperatESs]+0x6f): undefined reference to `OperationSub::OperationSub()'
说的是构造函数没有实现的问题,需要给构造函数加入实现。
网友评论