Factory is a design pattern in common usage. Implement aShapeFactorythat can generate correct shape.

You can assume that we have only tree different shapes:Triangle,Square_and_Rectangle.

Have you met this question in a real interview?

Yes

Example

ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape("Square");
shape.draw();

>
>
  ----

>
>
 |    |

>
>
 |    |

>
>
  ----

shape = sf.getShape("Triangle");
shape.draw();

>
>
   /\

>
>
  /  \

>
>
 /____\

shape = sf.getShape("Rectangle");
shape.draw();

>
>
  ----

>
>
 |    |

>
>
  ----
/**
 * Your object will be instantiated and called as such:
 * ShapeFactory* sf = new ShapeFactory();
 * Shape* shape = sf->getShape(shapeType);
 * shape->draw();
 */
class Shape {
public:
    virtual void draw() const=0;
};

class Rectangle: public Shape {
    // Write your code here
    void draw() const {
        cout << " ---- " << endl;
        cout << "|    |" << endl;
        cout << " ---- " << endl;
    }
};

class Square: public Shape {
    // Write your code here
    void draw() const {
        cout << " ---- " << endl;
        cout << "|    |" << endl;
        cout << "|    |" << endl;
        cout << " ---- " << endl;
    }
};

class Triangle: public Shape {
    // Write your code here
    void draw() const {
        cout << "  /\\  " << endl;
        cout << " /  \\ " << endl;
        cout << "/____\\" << endl;
    }
};

class ShapeFactory {
public:
    /**
     * @param shapeType a string
     * @return Get object of type Shape
     */
    Shape* getShape(string& shapeType) {
        // Write your code here
        Shape* shape = NULL;
        if (shapeType == "Square")
            shape = new Square();
        else if (shapeType == "Triangle")
            shape = new Triangle();
        else if (shapeType == "Rectangle")
            shape = new Rectangle();

        return shape;
    }
};

results matching ""

    No results matching ""