C++实现简单工厂模式

一,项目简介

       利用简单工厂模式完成简易的计算器,可以实现加减乘除运算。

       工具:vs2013编译器,windows平台

二,UML类图

C++实现简单工厂模式_第1张图片

三,代码

operationFactory : class
#pragma once
#include"Operation.h"

//简单工厂类
class OperationFactory
{
public:

	static Operation* creationOperate(char ch)
	{
		Operation* oper = nullptr;
		switch (ch)
		{
		case '+':
			oper = new OperationAdd();
			break;
		case '-':
			oper = new OperationSub();
			break;
		case '*':
			oper = new OperationMul();
			break;
		case '/':
			oper = new OperationDiv();
			break;
		default:
			printf("无%c运算符!\n",ch);
			break;
		}
		return oper;
	}
};


Operation:class
#pragma once
#include
using namespace std;

//运算类
class Operation
{
	 
private:
	double _numberA;
	double _numberB;
public:
	double GetA()const { return _numberA; }
	double GetB()const { return _numberB; }
	void SetA(double a){ _numberA = a; }
	void SetB(double b){ _numberB = b; }
	Operation() :_numberA(0), _numberB(0){}
	double virtual  GetResult(){ return 0; }

};
//加法类
class OperationAdd : public Operation
{
private:
	
public:
	double GetResult() override
	{
		return GetA() + GetB();
	}
};

//减法类
class OperationSub :public  Operation
{
public:
	double GetResult() override
	{
		return GetA() - GetB();
	}
};

//乘法类
class OperationMul :public  Operation
{
public:
	double GetResult() override
	{
		return GetA() * GetB();
	}
};

//除法类
class OperationDiv :public Operation
{
public:
	double GetResult() override
	{
		if (0 != GetB())
			return GetA() / GetB();
		else
		{
			printf("除数不能为0!\n");
			return 0;
		}
			
	}
};
main : 
#include
using namespace std;

#include"Operation.h"
#include"OperationFactory.h"

int main()
{
	double a = 2;
	double b = 3;

	OperationFactory operFactory;
	Operation* oper = operFactory.creationOperate('/');
	oper->SetA(a);
	oper->SetB(b);

	cout<<"a + b = "<< oper->GetResult()<

四,实现结果

C++实现简单工厂模式_第2张图片C++实现简单工厂模式_第3张图片C++实现简单工厂模式_第4张图片C++实现简单工厂模式_第5张图片

你可能感兴趣的:(C/C++,设计模式)