C++實現簡單工廠模式

一,項目簡介

       利用簡單工廠模式完成簡易的計算器,可以實現加減乘除運算。

       工具:vs2013編譯器,windows平臺

二,UML類圖


三,代碼

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<iostream>
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<iostream>
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()<<endl;
	return 0;
}

四,實現結果


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章