概述
在简单工厂模式中,可以根据参数的不同返回不同类的实例。简单工厂模式专门定义一个类来负责创建其他类的实例,被创建的实例通常都具有共同的父类。
优点
客户端无须知道所创建的具体产品类的类名,只需要知道具体产品类所对应的参数即可。
缺点
系统扩展困难,一旦添加新产品就不得不修改工厂逻辑,在产品类型较多时,有可能造成工厂逻辑过于复杂,不利于系统的扩展和维护。
类图
代码块
#include <iostream>
using namespace std;
class Product
{
public:
virtual int use() = 0;
protected:
string m_type;
};
class ProductA : public Product
{
public:
ProductA(){ m_type = "A"; }
virtual int use()
{
cout << "use in the " << m_type << endl;
return 0;
}
};
class ProductB : public Product
{
public:
ProductB() { m_type = "B"; }
virtual int use()
{
cout << "use in the " << m_type << endl;
return 0;
}
};
class Factory
{
public:
static Product *createProduct(string type)
{
if(type == "A")
{
return new ProductA();
}
else if(type == "B")
{
return new ProductB();
}
else
{
return NULL;
}
}
};
int main()
{
Product *pro = Factory::createProduct("B");
pro->use();
delete pro;
return 0;
}
参考
https://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/simple_factory.html