设计模式C++实现一:简单工厂模式

本文通过工厂模式实现了一个简单的计算器程序,该程序能够根据用户输入的不同运算符(加、减、乘、除),创建相应的运算对象并进行计算。通过对不同运算方式的抽象和封装,展示了工厂模式在代码复用性和扩展性上的优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考大话设计模式和网上的一些资料,自己编写下一些简单的设计模式,让自己了解这些设计模式的妙处!


#ifndef OPERATION_H
#define OPERATION_H
#include<iostream>
using namespace std;

class Operation
{
	
protected:
	double opA, opB;
public:	
	bool SetValue(double& n, double& m);
	virtual double GetResult()const=0;
};

class OperationAdd :public Operation
{
	double GetResult()const;
};

class  OperationSub :public Operation
{
	double GetResult()const;
};

class OperationMul :public Operation
{
	double GetResult()const;
};

class OperationDiv :public Operation
{
	double GetResult()const;
};

class OperationFactory
{
public:
	Operation * CreatOperation(char& operate);
};

bool Operation::SetValue(double &n, double &m)
{
	opA = n;
	opB = m;
	return true;
}

double OperationAdd::GetResult()const
{
	double result;
	result = opA + opB;
	return result;
}

double OperationSub::GetResult()const
{
	double result;
	result = opA - opB;
	return result;
}

double OperationMul::GetResult()const
{
	double result;
	result = opA * opB;
	return result;
}

double OperationDiv::GetResult()const
{
	if (opB == 0){ cout << "opB in OperationDiv can't be zero.\n"; return 0.00000001;}
	double result;
	result = opA / opB;
	return result;
}

Operation * OperationFactory::CreatOperation(char& operate)
{
	Operation * Oper = NULL;
	switch (operate)
	{
	case('+') :
		Oper = new OperationAdd;
		break;
	case('-') :
		Oper = new OperationSub;
		break;
	case('*') :
		Oper = new OperationMul;
		break;
	case('/') :
		Oper = new OperationDiv;
		break;
	default:
		break;
	}
	return Oper;
}

#endif

#include"operation.h"

int main()
{
	double numA, numB;
	char op;
	
	Operation * Oper;
	OperationFactory OpFa;
	cout << "Please enter the numbers and operation(A op B)";
	while (cin>>numA&&cin>>op&&cin>>numB){
		Oper = OpFa.CreatOperation(op);
		Oper->SetValue(numA, numB);
		cout << "The result of " << numA << op << numB << "= " << Oper->GetResult() << endl;
		cout << "Please enter the numbers and operation(A op B)";
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值