工厂方法模式(c++实现)

工厂方法模式

工厂方法模式其实也很简单,先放一张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. 迪米特法则

参考《大话设计模式》和 https://design-patterns.readthedocs.io/zh_CN/latest/index.html

posted @ 2020-04-14 11:40  鬼谷子com  阅读(1197)  评论(0编辑  收藏  举报