C++实现设计模式之 — 简单工厂模式

本文参考了程洁的大话模式还有网络上的一些代码。。。

所谓简单工厂模式,是一种实例化对象的方式,只要输入需要实例化对象的名字,就可以通过工厂对象的相应工厂函数来制造你需要的对象。
简单工厂模式的核心是,对于一个父类的多个继承子类,工厂对象的工厂函数根据用户输入,自动new出一个子类对象并返回其父类的指针,这样利用父类的指针执行父类的虚函数,就可以动态绑定子类的重写函数,从而实现多态。
对于一个只拥有加减乘除运算的简单计算器,我们设计一个Operation的父类,并构造加减乘除四个类继承父类重写运算函数GetResult。然后定义工厂类中的工厂函数,其根据用户的输入new出相应的对象实例并返回其父类的指针。

C++代码如下所示:

  1 / vectortest.cpp : 定义控制台应用程序的入口点。
  2 //
  3 #include "stdafx.h"
  4 #include <stdlib.h>
  5 #include <stdio.h>
  6 #include <string.h>
  7 #include<iostream>
  8 using namespace std;
  9 class Operation
 10 {
 11 private:
 12  double A;
 13  double B;
 14 public:
 15  double GetA() const {return A;}
 16  double GetB() const {return B;}
 17  void SetA(double x){A = x;}
 18  void SetB(double y){B = y;}
 19  double virtual GetResult(){return 0;}
 20  Operation():A(0),B(0){}
 21 };
 22 class OperationAdd:public Operation
 23 {
 24 public:
 25  double GetResult() override
 26  {
 27   return GetA()+ GetB();
 28  }
 29 };
 30 class OperationSub:public Operation
 31 {
 32 public:
 33  double GetResult() override
 34  {
 35   return GetA()- GetB();
 36  }
 37 };
 38 class OperationMul:public Operation
 39 {
 40 public:
 41  double GetResult() override
 42  {
 43   return GetA()*GetB();
 44  }
 45 };
 46 class OperationDiv:public Operation
 47 {
 48 public:
 49   double GetResult() override
 50  {
 51   double numberB = 0;
 52   double result = 0;
 53   numberB = GetB();
 54   //if(numberB == 0)
 55   //{
 56   // throw new Exception("除数不能为0!")
 57   //}
 58   result = GetA()/GetB();
 59   return result;
 60  }
 61 };
 62 class SimpleFactory
 63 {
 64 public:
 65  static Operation *CreateOpeartor(char ch)
 66  {
 67   Operation *p;
 68   switch(ch)
 69   {
 70   case '+':
 71    p = new OperationAdd();
 72    break;
 73   case '-':
 74    p = new OperationSub();
 75    break;
 76   case '*':
 77    p = new OperationMul();
 78    break;
 79   case '/':
 80    p = new OperationDiv();
 81    break;
 82   }
 83   return p;
 84  }
 85 };
 86 int _tmain(int argc, _TCHAR* argv[])
 87 {
 88  double A = 0;
 89  double B= 0 ;
 90  char ch = '\0';
 91  cin>>A>>ch>>B;
 92  //shared_ptr<Operation> op(SimpleFactory::CreateOpeartor(ch));
 93  Operation *op = SimpleFactory::CreateOpeartor(ch);
 94  op->SetA(A);
 95  op->SetB(B);
 96  cout<<op->GetResult()<<endl;
 97  if(NULL != op)
 98  {
 99   delete op;
100   op = NULL;
101  }
102  system("pause"); 
103  return 0;
104 }

 

posted @ 2018-07-04 10:32  wxmwanggood  阅读(191)  评论(0编辑  收藏  举报