码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-05-09 16:38:55      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:c++   面向对象   设计模式   简单工厂模式   

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

技术分享

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


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

标签:c++   面向对象   设计模式   简单工厂模式   

原文地址:http://blog.csdn.net/shiwazone/article/details/45601519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!