一、说明
定义一个创建对象的接口,其子类去具体现实这个接口以完成具体的创建工作。如果需要增加新的产品类,只需要扩展一个相应的工厂类即可。
缺点:产品类数据较多时,需要实现大量的工厂类,这无疑增加了代码量。
二、代码
#ifndef WIDGET_H
#define WIDGET_H
#include <QString>
class product
{
virtual const QString& type()=0;
};
class shoe_product:public product
{
public:
shoe_product();
const QString & type() override;
private:
QString m_type;
};
class clothe_product:public product
{
public:
clothe_product();
const QString & type() override;
QString m_type;
};
class factory
{
virtual product* create()=0;
};
class shoe_factory:public factory
{
public:
shoe_factory();
product * create() override;
};
class clothe_factory:public factory
{
public:
clothe_factory();
product * create() override;
};
#endif // WIDGET_H
#include "widget.h"
shoe_product::shoe_product()
{
}
const QString &shoe_product::type()
{
return m_type;
}
clothe_product::clothe_product()
{
}
const QString &clothe_product::type()
{
return m_type;
}
shoe_factory::shoe_factory()
{
}
product *shoe_factory::create()
{
return new shoe_product;
}
clothe_factory::clothe_factory()
{
}
product *clothe_factory::create()
{
return new clothe_product;
}