简单工厂模式(c++实现)

代码以水果加工厂的产线为背景

先不谈其他,上代码

工厂类:
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();
结果:

 

 其实所有的设计模式都是为了对扩展开放,我们来看一下如果增加新的产品线需要修改哪些代码:

  1. SimpleFactory工厂类增加枚举 
    enum TYPE{
            APPLE,
            BANANA,
            PEAR,
            GRAPE
        };
  2. 增加Grape类
    class Grape: public ProductionLine
    {
    public:
        Grape();
        ~Grape();
    
        virtual void Product();
    };
  3. SimpleFactory.CreateProLine 增加case分支
    case GRAPE:
            proLine = new Grape();
            
  4. 使用的时候增加创建过程
    ProductionLine* line4 = factory->CreateProLine(SimpleFactory::GRAPE);
    if(line4)
      line4->Product();

    看起来效果还凑合哈,基本做到了对扩展开放,下面给出了各个步骤更通俗的解释(之后的博客中我也会尽量使用这个代码跟现实场景和决策映射的方式来阐述代码这样写的原因和好处):

  • 工厂类添加枚举就是厂长下达指令要增加一个Grape(葡萄)的产品线;

  • 添加的Grape类就是在工厂腾出了位置给新的Grape产品线;

  • 增加case分支就是新的产品线铺设好了;

  • 调用就是用新的产品线开始生产;

git地址:https://gitee.com/guiguzicom/Demo/tree/master/designPatterns/simpleFactory

这个是符合真实场景的模拟的,但是改动的地方还是有点多。没有做到对修改关闭,那么有没有更好地办法呢,关注我的博客,下一篇继续设计模式探索之旅~

posted @ 2020-03-13 09:55  鬼谷子com  阅读(2644)  评论(0编辑  收藏  举报