简单工厂模式
理论
简单工厂模式又叫静态方法模式(因为工厂类定义了一个静态方法)。现实生活中,工厂是负责生产产品的。同样在设计模式中,简单工厂模式我们可以理解为负责生产对象的一个类,称为“工厂类”。
作用:
将“类实例化的操作”与“使用对象的操作”分开,让使用者不用知道具体参数就可以实例化出所需要的类,从而避免了在客户端代码中显式指定,实现了解耦。
实例
用任意一种面向对象语言实现一个计算器控制台程序
UML类图
实现代码
#include <iostream> #include <string> using namespace std; class Operation { public: void GetNumber(double num1, double num2) { number_A = num1; number_B = num2; } virtual double GetResult() = 0; protected: double number_A; double number_B; }; class OperationAdd :public Operation { public: double GetResult() { return number_A + number_B; } }; class OperationSub :public Operation { public: double GetResult() { return number_A - number_B; } }; class OperationMul :public Operation { public: double GetResult() { return number_A * number_B; } }; class OperationDiv :public Operation { public: double GetResult() { if (number_B == 0) { cout << "除数不能为0" << endl; exit(0); } return number_A / number_B; } }; //工厂类 class OperationFactory { public: static Operation* cerateOperate(char operate) { switch (operate) { case('+'): return new OperationAdd; case('-'): return new OperationSub; case('*'): return new OperationMul; case('/'): return new OperationDiv; default: break; } } }; void test() { double num1, num2; char choice; cout << "请输入第一个数:" << endl; cin >> num1; cout << "您想进行的运算是:" << endl; cin >> choice; cout << "请输入第二个数:" << endl; cin >> num2; double result = 0; OperationFactory factory; Operation* operate = factory.cerateOperate(choice); //父类指针指向子类对象 operate->GetNumber(num1, num2); result = operate->GetResult(); cout << "num1 " << choice << " num2 = " << result << endl; delete operate; } int main() { test(); system("pause"); return 0; }