码迷,mamicode.com
首页 > 其他好文 > 详细

大话设计模式——第一章:简单工厂模式

时间:2015-03-15 18:03:05      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

#include<iostream>

#include<string>

#include<exception>//c++标准异常类型的库

using namespace std;

bad_exception somethingwrong;

//在c++中class默认的继承是private 而struct 默认的继承是public
//static 类静态成员函数,即与对象无关,在类中的值不是因实例化某个对象而改变.

class operation//运算类(基类)
{

public:
	 double numberA;
	 double numberB;

	virtual double GetResult()//虚函数GetResult来得到计算结果.
	{
		double result=0;
		return result;
	}
};

//加减乘除类,继承自算法类(运算类的各个子类)
class operationAdd:public operation
{
public:
	double GetResult()
	{
		return numberA+numberB;
	}
};
class operationSub:public operation
{
public:
	double GetResult()
	{
		return numberB-numberA;
	}
};

class operationMul:public operation
{
public:
	double GetResult()
	{
	    return numberA*numberB;
	}	
};

class operationDiv:public operation
{
public:
	double GetResult()
	{
		if(numberB==0)
			throw somethingwrong;
		return numberA/numberB;
	}	
};

//运算工厂类
class operationFactory
{
public:
	static operation* createoperation(char operate)
	{
		switch(operate)
		{
		case ‘+‘:
			return new operationAdd;
			break;
		case ‘-‘:
			return new operationSub;
			break;
		case ‘*‘:
			return new operationMul;
			break;
		case ‘/‘:
			return new operationDiv;
			break;
		}
	}
};

int main()
{
	//客户端的程序
	operation *a;
	a=operationFactory::createoperation(‘/‘);
	a->numberA=8;
	a->numberB=0;
	try{
		cout<<a->GetResult()<<endl;}
	catch(bad_exception &)
	{
		cerr<<"B不应该为0";
		cout<<endl;
	}
	system("pause");
	return 1;
}

  

大话设计模式——第一章:简单工厂模式

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4339990.html

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