C++设计模式 ==> 简单工厂模式

简述

简单工厂模式的核心在于使用一个工厂类根据需求动态生成子类对象。以计算器程序作为例子,加减乘除都分别作为运算类的子类,然后让工厂类根据要求动态实例化子类。


图示

简单工厂模式图示


代码实现

/////////////////////////////
//
// @ FileName : Operation.h
// @ Date : 2018-08-06 18:04
//
/////////////////////////////

#pragma once

#include <cstdio>
#include <iostream>
#include <windows.h>

class Operation
{
private:
	double _numberA;
	double _numberB;
public:
	Operation() :_numberA(0), _numberB(0) {}
	void setNumberA(double&);
	void setNumberB(double&);
	double getNumberA() const;
	double getNumberB() const;
	double virtual getResult()
	{
		return 0;
	}
};

void Operation::setNumberA(double& numberA)
{
	this->_numberA = numberA;
	return;
}

void Operation::setNumberB(double& numberB)
{
	this->_numberB = numberB;
	return;
}

double Operation::getNumberA() const
{
	return this->_numberA;
}

double Operation::getNumberB() const
{
	return this->_numberB;
}

class OperationAdd : public Operation
{
	double getResult()
	{
		return getNumberA() + getNumberB();
	}
};

class OperationSub : public Operation
{
	double getResult()
	{
		return getNumberA() - getNumberB();
	}
};

class OperationMul : public Operation
{
	double getResult()
	{
		return getNumberA() * getNumberB();
	}
};

class OperationDiv : public Operation
{
	double getResult()
	{
		if (getNumberB() > 0.0)
		{
			return getNumberA() / getNumberB();
		}
		else
		{
			MessageBox(NULL, "Div Args-2 Should Be Bigger than Zero!", "Error", MB_OK);
			ExitProcess(0);
		}
	}
};

class OperaionFactory
{
public:
	static Operation* createOperate(char&);
};

Operation* OperaionFactory::createOperate(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:
		MessageBox(NULL, "Symbol Error!", "Error", MB_OK);
		ExitProcess(0);
	}
	return oper;
}

/////////////////////////////
//
// @ FileName : SFM.cpp
// @ Date : 2018-08-06 18:04
//
/////////////////////////////

#include "Operation.h"

using namespace std;

int main(void)
{
	Operation *oper;
	double _numberA = 0;
	double _numberB = 0;
	char symbol = '\0';
	scanf("%lf %c %lf", &_numberA, &symbol, &_numberB);
	oper = OperaionFactory::createOperate(symbol);
	oper->setNumberA(_numberA);
	oper->setNumberB(_numberB);
	double result = oper->getResult();
	cout << result << endl;
	system("pause");
	return 0;
}
posted @ 2018-08-24 21:29  倚剑问天  阅读(189)  评论(0编辑  收藏  举报