动机:通过“对象创建”来绕开new,来避免对象创建(new)过程中所导致的紧耦合(依赖具体类),从而支持对象创建的稳定
设计关键:客户端完全不需要操作具体类,只需要提供要创建具体类的参数
优点:
- 实现了对象的创建和使用的分离
- 客户无需知道产品的类名,只需要传入响应的参数即可
- 客户端不改动的情况下,服务端新增或者更换具体的产品类功能显得更加灵活
缺点:
- 工厂类的职责过重,包含了加减乘除各个实例的创建,它一旦有问题,整个系统就挂了
- 当添加新的操作实例时,还得改动工厂类方法,违反了开放--封闭原则,不利于系统的维护和扩展
- 工厂类的static方法不利于继承形成等级结构
代码如下:
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<iostream>
using namespace std;
class Operation
{
public:
virtual int GetResult() = 0;
int m_num1;
int m_num2;
};
class OperationAdd :public Operation
{
public:
int GetResult()
{
return m_num1 + m_num2;
}
};
class OperationSub :public Operation
{
public:
int GetResult()
{
return m_num1 - m_num2;
}
};
class OperationMul :public Operation
{
public:
int GetResult()
{
return m_num1 * m_num2;
}
};
class OperationDiv :public Operation
{
public:
int GetResult()
{
return m_num1 / m_num2;
}
};
class OperationFactory
{
public:
static Operation* createOperation(char ch)
{
Operation* oper = nullptr;
switch (ch)
{
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;
oper = OperationFactory::createOperation('+');
oper->m_num1 = 1;
oper->m_num2 = 2;
cout << oper->GetResult() << endl;
delete oper;
return 1;
}