工厂方法模式

Posted wzxnote

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了工厂方法模式相关的知识,希望对你有一定的参考价值。

工厂方法模式

工厂方法模式其实也很简单,先放一张UML类图来看一下类结构:

技术图片

由图我们可以看出有两个基类:

  • BaseFactory
    • AppleFactory
    • PearFactory
  • Fruit
    • Apple
    • Pear

AppleFactory负责创建Apple类,PearFactory负责创建Pear类。下面放代码实现:

  • fruit.h
#ifndef FRUIT_H
#define FRUIT_H
class Fruit
{
public:
    Fruit();
    virtual ~Fruit();
    virtual void FruitType() = 0;
};

class Apple : public Fruit
{
public:
    Apple();
    virtual ~Apple() override;
    virtual void FruitType() override;
};

class Pear : public Fruit
{
    public:
    Pear();
    virtual ~Pear() override;
    virtual void FruitType() override;
};
#endif // FRUIT_H
  • fruit.cpp
#include <QDebug>
#include "fruit.h"


void Apple::FruitType()
{
    qDebug() << "I am an Apple";
}

void Pear::FruitType()
{
    qDebug() << "I am an Pear";
}
  • basefactory.h
#include "fruit.h"
class BaseFactory
{
public:
    BaseFactory();
    virtual ~BaseFactory();
    virtual Fruit* Produce() = 0;

protected:
    Fruit* m_Fruit;
};

class AppleFactory : public BaseFactory
{
public:
    AppleFactory();
    virtual ~AppleFactory() override;
    virtual Fruit* Produce() override;
};

class PearFactory : public BaseFactory
{
public:
    PearFactory();
    virtual ~PearFactory() override;
    virtual Fruit* Produce() override;
};

#endif // BASEFACTORY_H
  • basefactory.cpp
#include <QDebug>
#include "basefactory.h"

#define DELETEOBJECT(x) if(x != nullptr) { delete x; x = nullptr;}
BaseFactory::BaseFactory()
{

}

BaseFactory::~BaseFactory()
{
    DELETEOBJECT(m_Fruit);
}

AppleFactory::AppleFactory()
{

}

AppleFactory::~AppleFactory()
{

}

Fruit *AppleFactory::Produce()
{
    m_Fruit = new Apple();
    return m_Fruit;
}

PearFactory::PearFactory()
{

}

PearFactory::~PearFactory()
{

}

Fruit *PearFactory::Produce()
{
    m_Fruit = new Pear();
    return m_Fruit;
}
  • main.cpp
#include <QCoreApplication>
#include "basefactory.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    BaseFactory* factory = new AppleFactory();
    factory->Produce()->FruitType();

    factory = new PearFactory();
    factory->Produce()->FruitType();

    return a.exec();
}

main函数只用到了BaseFactory基类工厂,很好的实现了细节的隐藏从而增加了代码的复用性。

工厂方法模式遵照了以下几个设计原则:

  1. 依赖倒转原则
  2. 开放封闭原则
  3. 迪米特法则

以上是关于工厂方法模式的主要内容,如果未能解决你的问题,请参考以下文章

设计模式-简单工厂工厂方法模式抽象工厂模式详解

工厂方法模式

设计模式-工厂方法模式(Go实现)

C++工厂模式(简单工厂工厂方法抽象工厂)

C++工厂模式(简单工厂工厂方法抽象工厂)

设计模式---工厂模式