#497 Shape Factory

    xiaoxiao2025-08-21  8

    题目描述:

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

    You can assume that we have only tree different shapes:TriangleSquare 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(); >> ---- >> | | >> ---- 题目思路:

    就是virtual function问题。

    Mycode(AC = 3ms):

    /** * 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 if (shapeType == "Square") { Shape *shape = new Square(); return shape; } else if (shapeType == "Triangle") { Shape *shape = new Triangle(); return shape; } else { Shape *shape = new Rectangle(); return shape; } } };

    转载请注明原文地址: https://ju.6miu.com/read-1301884.html
    最新回复(0)