设计模式--简单工厂模式

1:简单设计模式

以计算器为例,为了熟悉模板,同时,使用了模板

模板实现放在.h中

此文件是.h

#pragma once
template <typename T>
class Operation
{
public:
	Operation();
	virtual ~Operation();
	virtual T getResult() = 0;;

	T numberA;
	T numberB;
	T result;
};


template <typename T>
class OperationAdd : public Operation<T>
{
public:
	OperationAdd();
	virtual ~OperationAdd();

	T getResult();

};

template <typename T>
class OperationSub : public Operation<T>
{
public:
	OperationSub();
	virtual ~OperationSub();

	T getResult();

};

template <typename T>
class OperationMul : public Operation<T>
{
public:
	OperationMul();
	virtual ~OperationMul();

	T getResult();

};

template <typename T>
class OperationDiv : public Operation<T>
{
public:
	OperationDiv();
	virtual ~OperationDiv();

	T getResult();

};



template <typename T>
Operation<T>::Operation()
{
}

template <typename T>
Operation<T>::~Operation()
{
}



template <typename T>
OperationAdd<T>::OperationAdd()
{
};

template <typename T>
OperationAdd<T>::~OperationAdd()
{
}

template <typename T>
T OperationAdd<T>::getResult()
{
	this->result = this->numberA + this->numberB;
	return this->result;
	//return T();
};


template <typename T>
OperationSub<T>::OperationSub()
{
};

template <typename T>
OperationSub<T>::~OperationSub()
{
}

template <typename T>
T OperationSub<T>::getResult()
{
	this->result = this->numberA - this->numberB;
	return this->result;
	//return T();
};


template <typename T>
OperationMul<T>::OperationMul()
{
};

template <typename T>
OperationMul<T>::~OperationMul()
{
}

template <typename T>
T OperationMul<T>::getResult()
{
	this->result = this->numberA * this->numberB;
	return this->result;
	//return T();
};

template <typename T>
OperationDiv<T>::OperationDiv()
{
};

template <typename T>
OperationDiv<T>::~OperationDiv()
{
}

template <typename T>
T OperationDiv<T>::getResult()
{
	if (this->numberB == 0)
	{
		std::cout << "input error" << std::endl;
		return T();
	}
	this->result = this->numberA / this->numberB;
	return this->result;
	//return T();
};

main函数

	Operation<int>* operation = nullptr;
	char a = 0;
	scanf_s("%c",&a);
	switch (a)
	{
	case '+': 
		operation = new OperationAdd<int>();
		break;
	case '-':
		operation = new OperationSub<int>();
		break;
	case '*':
		operation = new OperationMul<int>();
		break;
	case '/':
		operation = new OperationDiv<int>();
		break;
	}
	operation->numberA = 1;
	operation->numberB = 3;
	std::cout << operation->getResult() << std::endl;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值