vendredi 10 août 2018

Sample Factory Pattern Output not displaying

I'm trying to implement the GoF Factory Pattern, but for some reason I am not getting the output.

PS. All the files below have been compiled with -std=gnu++14 parameter.

Below is a shape.h header file where I have defined an (abstract) class Shape

class Shape
{
    public:
        virtual void draw() {}
};

Now I have another header file shapes.h where I have written three concrete classes that extend the Shape class. I have also overridden the draw() inside each of these classes.

#include "shape.h"
#include <iostream>

using std::cout;

class Circle : public Shape
{
    public:
        void draw()
        {
            cout << "Inside Circle::draw()\n";
        }
};

class Square : public Shape
{
    public:
        void draw()
        {
            cout << "Inside Square::draw()\n";
        }
};

class Rectangle : public Shape
{
    public:
        void draw()
        {
            cout << "Inside Rectangle::draw()\n";
        }
};

Now I have a Shapefactory class, defined in shapefactory.h that will give me a Shape depending upon the parameter passed in the function:

#include "shapes.h"
#include <string>
#include <algorithm>

using std::string;

class Shapefactory
{
    private:
        bool iequals(const string& a, const string& b)
        {
            return std::equal
                (a.begin(), a.end(),
                b.begin(), b.end(),
                [](char a, char b) {
                    return tolower(a) == tolower(b);
                }
            );
        }
    public:
        Shape get_shape(string shape)
        {
            if (iequals(shape , "CIRCLE"))
                return Circle();
            else if (iequals(shape , "SQUARE"))
                return Square();
            else if (iequals(shape , "RECTANGLE"))
                return Rectangle();
            else
                return Circle();
        }
};

Finally here is the our driver program:

#include "shapefactory.h"

int main()
{
    Shapefactory shapeFactory;
    Shape shape1 = shapeFactory.get_shape("CIRCLE");
    shape1.draw();

    Shape shape2 = shapeFactory.get_shape("RECTANGLE");
    shape2.draw();

    Shape shape3 = shapeFactory.get_shape("SQUARE");
    shape3.draw();

    return 0;
}

None of the shape's draw() gives an output. Where am I going wrong?

Aucun commentaire:

Enregistrer un commentaire