一、说明
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式作为一种创建模式,一般在创建复杂对象时,考虑使用;在创建简单对象时,建议直接new完成一个实例对象的创建。
主要特点是需要在工厂类中做判断,从而创造相应的产品,当增加新产品时,需要修改工厂类。使用简单工厂模式,我们只需要知道具体的产品型号就可以创建一个产品。
缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。
二、代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QString>
typedef enum
{
product_shoe,
product_clothe
}product_type;
//抽象产品类
class product
{
public:
virtual const QString& type() = 0;
};
//具体产品类
class shoe : public product
{
public:
shoe();
const QString & type() override;
private:
QString m_type;
};
//具体产品类
class clothe : public product
{
public:
clothe();
const QString & type() override;
private:
QString m_type;
};
//工程类
class factory
{
public:
factory();
product* createProdut(const product_type& type);
};
#endif // WIDGET_H
#include "widget.h"
shoe::shoe()
{
}
const QString &shoe::type()
{
return m_type;
}
clothe::clothe()
{
}
const QString &clothe::type()
{
return m_type;
}
factory::factory()
{
}
product *factory::createProdut(const product_type &type)
{
switch(type)
{
case product_shoe:
return new shoe();
case product_clothe:
return new clothe();
default:
return nullptr;
}
}