首页 > 其他 > 详细

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

时间:2014-03-14 23:16:19      阅读:635      评论:0      收藏:0      [点我收藏+]

实例:

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


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;
}

参考:

大话设计模式

Design Patterns----简单的工厂模式,布布扣,bubuko.com

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

原文:http://blog.csdn.net/shoulinjun/article/details/21241365

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!