工厂方法C ++实现

时间:2016-10-15 13:49:04

标签: c++ qt design-patterns

我想知道这段代码是否能完成纯工厂方法设计模式要求的所有内容?这是为我的最终编程模块做准备,我只需要确保这是设计模式的正确应用。

#include <QCoreApplication>
#include <QString>
#include <QDebug>

class Bread
{
public:
    virtual void print() = 0;
};

class WhiteBread: public Bread
{
public:
    void print() {
        qDebug() << "White bread";
    }
};

class BrownBread: public Bread
{
public:
    void print() {
        qDebug() << "Brown bread";
    }
};

class BreadFactory {
public:
    Bread* makeBread(QString type) {
        if (type == "White bread")
            return new WhiteBread();
        else if (type == "Brown bread")
            return new BrownBread();
    }
};


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

    BreadFactory *breadFactory = new BreadFactory();
    Bread *breadType;

    breadType= breadFactory->makeBread("White bread");
    breadType->print();

    breadType = breadFactory->makeBread("Brown bread");
    breadType->print();

    return a.exec();
}

2 个答案:

答案 0 :(得分:2)

  1. 您无需创建实例BreadFactory。只需使用静态方法。

    class BreadFactory
    {
        public:
            static Bread* makeBread( QString type ) 
            {
            ...
            }
    };
    
    //in main 
    Bread *breadType = BreadFactory::makeBread( "White Bread"); 
    breadType->print();
    
  2. 为清晰起见,请使用c ++ 11 override关键字。

    class WhiteBread : public Bread
    {
    public:
        void print() override{
    ...
    
  3. 在智能指针中使用c ++ 11 unique_ptr

    static unique_ptr<Bread> makeBread( QString type ) {
        if ( type == "White bread" )
            return std::make_unique<WhiteBread>();
        else if ( type == "Brown bread" )
            return std::make_unique<BrownBread>();
        else
            return nullptr;
    }
    
  4. 使用virtual析构函数。

    class Bread
    {
    public:
        virtual void print() = 0;
        virtual ~Bread() {};
    };
    

答案 1 :(得分:0)

工厂方法实现如下:

class BreadMaker
{
 public:
   virtual Bread* makeBread() = 0;
}

class WhiteBreadMaker : public BreadMaker
{
public:
   Bread* makeBread();
}

// WhiteBreadMaker.cpp
Bread* WhiteBreadMaker::makeBread()
{
   return new WhiteBread();
}

// ***Similarly for BrownBreadMaker

// main.cpp
int main()
{
   BreadMaker *maker = new WhiteBreadMaker();    // or BrownBreadMaker

   Bread *bread = maker->makeBread();
   bread->print();    // prints "White Bread" or "Brown Bread" depending on the Factory class used.
}