1. 程式人生 > >C++設計模式-繼承與多型影響耦合性(最基礎的簡單工廠模式小例項)

C++設計模式-繼承與多型影響耦合性(最基礎的簡單工廠模式小例項)

繼承與多型影響耦合性(最基礎的簡單工廠模式小例項)

原理:
通過繼承和虛擬函式的方式修改某個子類對應函式的功能;
通過簡單工廠模式到底例項化誰;

如果要增加複雜的運算只有增加響應的子類,以及工廠的分支即可;

 

程式執行截圖如下:

 

目錄結構如下:

 

原始碼如下:

OperationFactory.h

#pragma once

#include "Operation.h"
#include "OtherOperation.h"
#include <iostream>
#include <string>
using namespace std;

class OperationFactory{
public:
	static Operation *createOperate(string operateStr){
		Operation *operation;

		if(operateStr == "+")
			operation = new OperationAdd;
		else if(operateStr == "-")
			operation = new OperationSub;
		else if(operateStr == "*")
			operation = new OperationMul;
		else if(operateStr == "/")
			operation = new OperationDiv;
		else 
			throw "The operation is wrong";

		return operation;
	}
};

Oeration.h

#pragma once
class Operation
{
public:
	double getNumberA();
	double getNumberB();

	void setNumberA(const double numberA);
	void setNumberB(const double numberB);

	virtual double getResult();
	virtual ~Operation();

//protected:
	double m_numberA;
	double m_numberB;
};

OtherOperation.h

#pragma once

#include "Operation.h"
#include <iostream>
using namespace std;

class OperationAdd:public Operation{
public:
	double getResult() override{
		return m_numberA + m_numberB;
	}

	~OperationAdd(){
		cout << "~OperationAdd called!" << endl;
	}
};

class OperationSub:public Operation{
public:
	double getResult() override{
		return m_numberA - m_numberB;
	}

	~OperationSub(){
		cout << "~OperationSub called!" << endl;
	}
};

class OperationMul:public Operation{
public:
	double getResult() override{
		return m_numberA * m_numberB;
	}

	~OperationMul(){
		cout << "~OperationMul called!" << endl;
	}
};

class OperationDiv:public Operation{
public:
	double getResult() override{
		if(m_numberB == 0)
			throw "The divisor cannot be 0";

		return m_numberA / m_numberB;
	}

	~OperationDiv(){
		cout << "~OperationDiv called!" << endl;
	}
};

main.cpp

#include "OperatinFactory.h"

int main(){

	double num1, num2;
	string operStr;

	cout << "Please in put NumA:";
	cin >> num1;
	cout << "Please in put operation:";
	cin >> operStr;
	cout << "Please in put NumB:";
	cin >> num2;

	Operation *oper;

	try{

		oper = OperationFactory::createOperate(operStr);
		oper->setNumberA(num1);
		oper->setNumberB(num2);
		cout << "The result is " << oper->getResult() << endl;
		delete oper;
	}
	catch(const char *msg){
		cout << "The error : " << msg << endl;
	}

	system("pause");
	return 0;
}

Operation.cpp

#include "Operation.h"
#include <iostream>
using namespace std;

double Operation::getNumberA()
{
	return m_numberA;
}

double Operation::getNumberB()
{
	return m_numberB;
}

void Operation::setNumberA(const double numberA)
{
	m_numberA = numberA;
}

void Operation::setNumberB(const double numberB)
{
	m_numberB = numberB;
}

double Operation::getResult()
{
	return 0.0;
}

Operation::~Operation()
{
	cout << "~Operation called" << endl;
}

 

UML類圖如下: