KO.
KO.

Reputation: 173

Factory method C++ implementation

I was wondering if this piece of code does everything the pure factory method design pattern asks for? This is in preparation for my final programming module and I just need to make sure that is is the correct application of the design pattern.

#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();
}

Upvotes: 1

Views: 3599

Answers (2)

coonal
coonal

Reputation: 93

A Factory Method implementation would be like this:

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.
}

Upvotes: 0

hyun
hyun

Reputation: 2143

  1. You don't need to make instance BreadFactory. Just use static method.

    class BreadFactory
    {
        public:
            static Bread* makeBread( QString type ) 
            {
            ...
            }
    };
    
    //in main 
    Bread *breadType = BreadFactory::makeBread( "White Bread"); 
    breadType->print();
    
  2. Use c++11 override keyword, for clarity.

    class WhiteBread : public Bread
    {
    public:
        void print() override{
    ...
    
  3. Use c++11 unique_ptr among smart pointer.

    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. Use virtual destructor.

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

Upvotes: 3

Related Questions