程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Design Patterns----簡單的工廠模式

Design Patterns----簡單的工廠模式

編輯:C++入門知識

實例:

實現一個簡單的計算器。實現加減乘除等操作。。


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

參考:

大話設計模式

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved