标签:info end 数字 ber case cte community res ase
一 包含的角色
简单工厂模式包含三个角色:
二 优势
实现了松耦合,当需要增加一种新产品(在大话设计模式中,例子是运算Operation),只需要做两点改动:
三 C++代码实现
开发环境 Visual Studio Community 2017
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
//抽象的产品类
class Operation
{
public:
double GetNumberA() const
{
return this->numberA;
}
double GetNumberB() const
{
return this->numberB;
}
void SetNumberA(const double A)
{
this->numberA = A;
}
void SetNumberB(const double B)
{
this->numberB = B;
}
virtual double GetResult()
{
double result = 0;
return result;
}
protected:
double numberA;
double numberB;
};
//下面是四种具体产品类
class OperationAdd : public Operation
{
public:
double GetResult()
{
double result = 0;
result = this->numberA + this->numberB;
return result;
}
};
class OperationSub : public Operation
{
public:
double GetResult()
{
double result = 0;
result = this->numberA - this->numberB;
return result;
}
};
class OperationMul : public Operation
{
public:
double GetResult()
{
double result = 0;
result = this->numberA * this->numberB;
return result;
}
};
class OperationDiv : public Operation
{
public:
double GetResult()
{
double result = 0;
if (numberB != 0)
{
result = this->numberA / this->numberB;
}
return result;
}
};
//到底要实例化谁,将来会不会增加实例化操作,比如增加开根运算
//应该考虑用一个单独的类来做这个创造实例的过程,这就是工厂
class OperationFactory
{
public:
static Operation* createOperate(char type)
{
Operation* oper = NULL;
switch (type)
{
case '+':
oper = new OperationAdd();
break;
case '-':
oper = new OperationSub();
break;
case '*':
oper = new OperationMul();
break;
case '/':
oper = new OperationDiv();
break;
default:
break;
}
return oper;
}
};
//客户端代码
int main()
{
Operation* oper;
double strNumberA;
double strNumberB;
char type;
cout << "请输入数字A" << endl;
cin >> strNumberA;
cout << "请输入数字B" << endl;
cin >> strNumberB;
cout << "请选择运算符号" << endl;
cin >> type;
oper = OperationFactory::createOperate(type);
oper->SetNumberA(strNumberA);
oper->SetNumberB(strNumberB);
cout << oper->GetResult() << endl;
if (oper != NULL)
{
delete oper;
oper = NULL;
}
return 0;
}
标签:info end 数字 ber case cte community res ase
原文地址:https://www.cnblogs.com/Manual-Linux/p/11099795.html