简单工厂模式通过定义一个类来根据传入的参数不同来返回不同类型的实例,创建实例的方法一般为静态方法。
下面是简单工厂模式的UML图:
下面来分析代码:
// 声明简单工厂类
class SimpleFactory
{
public:
enum TYPE{
APPLE,
BANANA,
PEAR
};
static SimpleFactory* GetInstance(); // 静态函数返回一个类的实例
ProductionLine *CreateProLine(TYPE type);
private:
SimpleFactory();
};
// 获取实例化对象
SimpleFactory *SimpleFactory::GetInstance()
{
static SimpleFactory factory;
return &factory;
}
ProductionLine *SimpleFactory::CreateProLine(TYPE type)
{
ProductionLine* proLine;
switch (type) {
case APPLE:
proLine = new AppleLine(); // 基类指针指向子类对象
break;
case BANANA:
proLine = new BananaLine();
break;
case PEAR:
proLine = new Pear();
break;
}
return proLine;
}
// 具体的产品线类
class ProductionLine
{
public:
ProductionLine();
virtual ~ProductionLine();
virtual void Product() = 0; // 纯虚函数 为子类提供接口继承
};
class AppleLine: public ProductionLine
{
public:
AppleLine();
~AppleLine();
virtual void Product();
};
class BananaLine: public ProductionLine
{
public:
BananaLine();
~BananaLine();
virtual void Product();
};
class Pear: public ProductionLine
{
public:
Pear();
~Pear();
virtual void Product();
};
// 虚函数重定义 生产具体的产品
void AppleLine::Product()
{
qDebug() << "product apple!"; // 子类重写虚函数,多态调用
}
void BananaLine::Product()
{
qDebug() << "product banana!";
}
void Pear::Product()
{
qDebug() << "product pear!";
}
// 具体使用
SimpleFactory* factory = SimpleFactory::GetInstance();
ProductionLine* line1 = factory->CreateProLine(SimpleFactory::APPLE);
ProductionLine* line2 = factory->CreateProLine(SimpleFactory::BANANA);
ProductionLine* line3 = factory->CreateProLine(SimpleFactory::PEAR);
if(line1)
line1->Product();
if(line2)
line2->Product();
if(line3)
line3->Product();