首页 > 代码库 > 工厂模式

工厂模式

通过大话设计模式一书学习后,c++编写的设计模式代码:

// OOTest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include "Operation.h"
#include "OperationFactory.h"

int _tmain(int argc, _TCHAR* argv[])
{
	double resurt=0;	
	OperationFactory factory;
	Operation *father = factory.createFactory('+');		
	father->setAB(2,3);
	resurt = father->getResurt();	
	cout << "add" << resurt << endl;

	system("pause");
	return 0;
}
---------------工厂类-----------
#pragma once
#include "iostream"
using namespace std;

#include "Operation.h"
#include "OperationAdd.h"
#include "OperationSub.h"
class OperationFactory
{
public:
	OperationFactory(void);
	~OperationFactory(void);
	

	Operation * createFactory(char operation);
};

#include "StdAfx.h"
#include "OperationFactory.h"

OperationFactory::OperationFactory(void)
{
}

OperationFactory::~OperationFactory(void)
{
}

Operation * OperationFactory::createFactory(char operation)
{
	Operation * oper = NULL ;
	switch(operation)
	{
	case '+':
			oper = new OperationAdd();
		break;
	case '-':
			oper = new OperationSub();
			break;
	default:
			cout << "err" << endl;
	}
	return oper;
}

---------------父类-----------
#pragma once

class Operation
{
public:
	Operation(void);
	virtual ~Operation(void);
	virtual double getResurt();
	void setAB(double numA, double numB);
public:
	double mNumberA;
	double mNumberB;
};

#include "StdAfx.h"
#include "Operation.h"

Operation::Operation(void)
{
}

Operation::~Operation(void)
{
}

double Operation::getResurt()
{
	return 0;
}
void Operation::setAB(double numA, double numB)
{
	this->mNumberA = numA;
	this->mNumberB = numB;
}

---------------ADD类-----------
#pragma once
#include "operation.h"

class OperationAdd :
	public Operation
{
public:
	OperationAdd(void);
	~OperationAdd(void);

	double getResurt();
	double getA();
};

#include "StdAfx.h"
#include "OperationAdd.h"

OperationAdd::OperationAdd(void)
{
}

OperationAdd::~OperationAdd(void)
{
}

double OperationAdd::getResurt()
{
	return mNumberA+mNumberB;
}
double OperationAdd::getA()
{
	return mNumberA;
}

---------------SUB类-----------
#pragma once
#include "operation.h"

class OperationSub :
	public Operation
{
public:
	OperationSub(void);
	~OperationSub(void);

	double getResurt();
};

#include "StdAfx.h"
#include "OperationSub.h"

OperationSub::OperationSub(void)
{
}

OperationSub::~OperationSub(void)
{
}

double OperationSub::getResurt()
{
	return mNumberA-mNumberB;
}