简单实现工厂模式

C++理解面向对象的思想:封装,继承,多态在工厂模式中体现,以计算器为例:加减乘除继承自接口类getResult接口实现获取预算结果

首先创建类似于接口类实现Opera.h:

#pragma once
class COperator
{
public:
	COperator(void);
	virtual ~COperator(void);
protected:
	double numbera;
	double numberb;
public:
	virtual double getResult() = 0;
	double getNumbera(){return numbera;}
	double getNumberb(){return numberb;}
};
Opera.cpp

#include "StdAfx.h"
#include "Operator.h"
COperator::COperator(void)
{
}
COperator::~COperator(void)
{
} 
继承类加操作实现add.h

#pragma once
#include "Operator.h"
class CAdd : public COperator
{
public:
	CAdd(void);
	~CAdd(void);
public:
	virtual double getResult();
};

add.cpp实现:

#include "StdAfx.h"
#include "Add.h"

CAdd::CAdd(void)
{
}
CAdd::~CAdd(void)
{
}
double CAdd::getResult()
{
	return numbera + numberb;
}
减法操作实现 subtraction.h:

#pragma once
#include "Operator.h"
class CSubtraction : public COperator 
{
public:
	CSubtraction(void);
	~CSubtraction(void);
public:
	virtual double getResult(){return numbera-numberb;}
};
subtraction.cpp 实现:

扫描二维码关注公众号,回复: 14457069 查看本文章
#include "StdAfx.h"
#include "Subtraction.h"

CSubtraction::CSubtraction(void)
{
}
CSubtraction::~CSubtraction(void)
{
}

乘除的实现就不列举了,如果再加新的操作,直接继承自接口类实现即可,这样就不用影响其他已经实现的算法操作,直接增加新的操作类即可,接着是比较重要的实现如何使用工厂产生这些操作:

CreateOperato.h实现:

#pragma once
#include "Operator.h"
#include <string>
using namespace std;

class CCreateOperator
{
public:
	CCreateOperator(void);
	~CCreateOperator(void);
public:
	static COperator* creatorOperator(string strOper);
};


CreateOperato.cpp实现:

#include "StdAfx.h"
#include "CreateOperator.h"
#include "Subtraction.h"
#include "Add.h"

CCreateOperator::CCreateOperator(void)
{
}
CCreateOperator::~CCreateOperator(void)
{
}

COperator* CCreateOperator::creatorOperator(string strOper)
{
	COperator* pOper = NULL;
	if(strOper == "+")
	{
		pOper = new CAdd;
	}else if(strOper == "-")
	{

		pOper = new CSubtraction;
	}
	return pOper;
}

main.cpp实现:

#include "stdafx.h"
#include "Operator.h"
#include "CreateOperator.h"

int _tmain(int argc, _TCHAR* argv[])
{
	COperator* pOper = CCreateOperator::creatorOperator("+");

	pOper->numbera = 1;
	pOper->numberb = 2;

	double dResult = pOper->getResult();
	printf("result:%f",dResult);

	
	return 0;
}

写的太拙劣请大家指正,还有很多地方写的不太好请给出宝贵的建议。

猜你喜欢

转载自blog.csdn.net/huangyifei_1111/article/details/77151090