工厂模式
复习《大话设计模式》中的《工厂模式》
工厂模式即实例化对象,即c++中new一个对象,其中运用面向对象继承,多态;降低了模块与模块的耦合度。
书中的例子:
UML(unified modeling language)
示例代码:
#ifndef OPERATOR_H #define OPERATOR_H #include <cstring> #include <QDebug> /*抽象基类*/ class Operator { public: Operator(double n1 = 0, double n2 = 0); virtual double getResult() = 0; protected: double num1; double num2; }; Operator::Operator(double n1, double n2) { num1 = n1; num2 = n2; }; /*子类*/ class Add:public Operator /*继承*/ { public: Add(double n1, double n2):Operator(n1, n2){}; double getResult(); }; double Add::getResult() { double temp = num1 + num2; return temp; }; class Sub:public Operator { public: Sub(double n1, double n2):Operator(n1, n2){}; double getResult(); }; double Sub::getResult() { double temp = num1 - num2; return temp; }; class Multiple:public Operator { public: Multiple(double n1, double n2):Operator(n1, n2){}; double getResult(); }; double Multiple::getResult() { double temp = num1 * num2; return temp; }; class Divide:public Operator { public: Divide(double n1, double n2):Operator(n1, n2){}; double getResult(); }; double Divide::getResult() { double temp = 0; if(num2 == 0) { throw num2; goto End; } temp = num1 / num2; End: return temp; }; /*工厂类*/ class Factory { public: Operator * createOperator(int operate, double n1 = 0, double n2 = 0); ~Factory(); protected: Operator *oper; }; Factory::~Factory() { if(oper != NULL) delete oper; oper = NULL; } /*实例化,返回基类指针*/ Operator * Factory::createOperator(int operate, double n1, double n2) { oper = NULL; switch(operate) { case '+': oper = new Add(n1, n2); /*多态oper指向Add类*/ break; case '-': oper = new Sub(n1, n2); break; case '*': oper = new Multiple(n1, n2); break; case '/': oper = new Divide(n1, n2); break; default: oper = NULL; } return oper; } #endif