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

四,实现结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值