L_J_SHOU

Design Patterns----简单的工厂模式

实例:

实现一个简单的计算器。实现加减乘除等操作。。


operator.h 文件

// copyright @ L.J.SHOU Mar.13, 2014
// a simple calculator using Factory Design Pattern
#ifndef OPERATOR_H_
#define OPERATOR_H_

#include <string>
#include <iostream>
#include <stdexcept>

// 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 <iostream>
#include <stdexcept>
#include "boost/shared_ptr.hpp"
using namespace std;

int main(void)
{
  try{
    boost::shared_ptr<Operator> pOper(createOperator("+", 0, 1));
    cout << pOper->GetResult() << endl;

    pOper = boost::shared_ptr<Operator>(createOperator("-", 0, 1));
    cout << pOper->GetResult() << endl;

    pOper = boost::shared_ptr<Operator>(createOperator("*", 2, 3));
    cout << pOper->GetResult() << endl;

    pOper = boost::shared_ptr<Operator>(createOperator("/", 1, 0));
    cout << pOper->GetResult() << endl;
  }
  catch(std::runtime_error err){
    std::cout << err.what() 
              << std::endl;
  }

  return 0;
}

参考:

大话设计模式

posted on 2014-03-14 16:56  L_J_SHOU  阅读(134)  评论(0)    收藏  举报