简单工厂模式

        把《大话设计模式》完全地看完了,确实很通俗易懂。但是书上得来终觉浅,还是好好把书中的代码实现一遍吧。

        简单工厂模式,在书中的定义就是用一个单独的类来做这个创造实例的过程。即把各个不同对象的创建代码封装成一个类。个人感觉这个方式确实很不错,因为每一个类对象就可以在其需要的时候灵活地创建,而且实现方法还可以在各自类中定义,容易修改而不互相影响。下面就按照书本上的例子,用C++来实现一次。

   实现运算类的文件:   

#include <iostream>
#include <string.h>
using namespace std;
#pragma once


class Operation
{
  /*protected:     //protected:derived class can use it
	 double numberA;
	 double numberB;*/

  public:
	 double numberA;
	 double numberB;

	  virtual double GetResult()=0;//???
};

class OperationAdd : public Operation //must add a key word "public" ,so that the pointer 
{                                     //of base class can point to derived class
   public:
	   double GetResult()
	   {
	     double result = 0;
		 result = numberA+numberB;
		 return result;    
	   }
};

class OperationSub : public Operation
{
   public:
	   double GetResult()
	   {
		  double result = 0;
		  result = numberA-numberB;
		  return result;
	   }
};

class OperationMul : public Operation
{  
   public:
	   double GetResult()
	   {
	      double result = 0;
		  result = numberA*numberB;
		  return result;
	   }
};

class OperationDiv : public Operation
{
    public:
		double GetResult()
		{
		  double result = 0;
		  if(numberB == 0)
		    cout<<"除数不能为0!";
		  else 
		    result = numberA/numberB;
		  return result;
	    }
};

class OperationFactory
{
    public:
		// Operation* createOperate(char operation);
		Operation* createOperate(char operate)
{
    Operation *oper;
    switch(operate)
	{
	   case '+':
		   {
		      oper = new OperationAdd();
		      break;
		   }
	   case '-':
		   {
		      oper = new OperationSub();
			  break;
		   }
	   case '*':
		   {
		      oper = new OperationMul();
			  break;
		   }
	   case '/':
		   {
		      oper = new OperationDiv();
			  break;
		   }
	   default:
		   cout<<"wrong input!!!";
	}
	    return oper;
} 
};


主程序:

#include "stdafx.h"
#include "Operation.h"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	char operate;
	double A,B;
	cout<<"请输入数字A:";
	cin>>A;
	cout<<endl<<"请输入运算符+、-、*、/:";
	cin>>operate;
	cout<<endl<<"请输入数字B:";
	cin>>B;
	cout<<endl;
	
	Operation *op;
	OperationFactory of;

	op = of.createOperate(operate);
	op->numberA = A;
	op->numberB = B;
	cout<<op->GetResult();
	cin>>A;
	return 0;
}


          只是简单的实践,主要是为了锻炼一下自己的理解和模式的锻炼。其中还是遇到一些小问题,看来面向对象的编程还不是很熟练,要慢慢锻炼。

你可能感兴趣的:(设计模式,编程,c,Class,input)