實例:
實現一個簡單的計算器。實現加減乘除等操作。。
operator.h 文件
// copyright @ L.J.SHOU Mar.13, 2014 // a simple calculator using Factory Design Pattern #ifndef OPERATOR_H_ #define OPERATOR_H_ #include#include #include // base class class Operator { public: Operator(double lhs, double rhs) : numberA(lhs), numberB(rhs){} virtual double GetResult() = 0; protected: double numberA; double numberB; }; // "+" class OperatorAdd : public Operator { public: OperatorAdd(double lhs, double rhs) : Operator(lhs, rhs) { } double GetResult() { return numberA + numberB; } }; // "-" class OperatorMinus : public Operator { public: OperatorMinus(double lhs, double rhs) : Operator(lhs, rhs) { } double GetResult() { return numberA - numberB; } }; // "*" class OperatorMul : public Operator { public: OperatorMul(double lhs, double rhs) : Operator(lhs, rhs) { } double GetResult() { return numberA * numberB; } }; // "/" class OperatorDiv : public Operator { public: OperatorDiv(double lhs, double rhs) : Operator(lhs, rhs) { } double GetResult() { if(numberB == 0) throw std::runtime_error("divide zero !!!"); return numberA / numberB; } }; // factory function Operator* createOperator(std::string oper, double lhs, double rhs) { Operator* pOper(NULL); if(oper == "+") { pOper = new OperatorAdd(lhs, rhs); } else if(oper == "-") { pOper = new OperatorMinus(lhs, rhs); } else if(oper == "*") { pOper = new OperatorMul(lhs, rhs); } else if(oper == "/") { pOper = new OperatorDiv(lhs, rhs); } else { std::cerr << "not a valid operator" << std::endl; return NULL; } return pOper; } #endif
operator.cc 文件
// copyright @ L.J.SHOU Mar.13, 2014 // a simple calculator using Factory Design Pattern #include "operator.h" #include#include #include "boost/shared_ptr.hpp" using namespace std; int main(void) { try{ boost::shared_ptr pOper(createOperator("+", 0, 1)); cout << pOper->GetResult() << endl; pOper = boost::shared_ptr (createOperator("-", 0, 1)); cout << pOper->GetResult() << endl; pOper = boost::shared_ptr (createOperator("*", 2, 3)); cout << pOper->GetResult() << endl; pOper = boost::shared_ptr (createOperator("/", 1, 0)); cout << pOper->GetResult() << endl; } catch(std::runtime_error err){ std::cout << err.what() << std::endl; } return 0; }
參考:
大話設計模式