[LintCode][System Design] Shape Factory

Problem

More LeetCode Discussions

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

Example

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

 ----
|    |
|    |
 ----

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

  /\
 /  \
/____\

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

 ----
|    |
 ----

Solution

class Shape {
public:
    virtual void draw() const=0;

    void drawHorizontalLine() const {
        drawSpace(1);
        for(int i = 0; i < 4; i++) {
            cout << '-';
        }
        drawSpace(1);
        cout << endl;
    }

    void drawVerticalLine() const {
        cout << '|';
        drawSpace(4);
        cout << '|' << endl;
    }

    void drawSpace(int n) const {
        for(int i = 0; i < n; i++) {
            cout << ' ';
        }
    }
};

class Rectangle: public Shape {
public:
    void draw() const {
        drawHorizontalLine();
        drawVerticalLine();
        drawHorizontalLine();
    }
};

class Square: public Shape {
public:
    void draw() const {
        drawHorizontalLine();
        drawVerticalLine();
        drawVerticalLine();
        drawHorizontalLine();
    }
};

class Triangle: public Shape {
public:
    void draw() const {
        drawSpace(2);
        cout << "/\\" << endl;
        drawSpace(1);
        cout << '/';
        drawSpace(2);
        cout << '\\' << endl;
        cout << '/';
        for(int i = 0; i < 4; i++) {
            cout << '_';
        }
        cout << '\\' << endl;
    }
};

class ShapeFactory {
private:
    const string squareType = "Square";
    const string triangleType = "Triangle";
    const string rectType = "Rectangle";

public:
    /**
     * @param shapeType a string
     * @return Get object of type Shape
     */
    Shape* getShape(string& shapeType) {
        if (shapeType == squareType) {
            return new Square();
        } else if (shapeType == rectType) {
            return new Rectangle();
        } else if (shapeType == triangleType) {
            return new Triangle();
        }

        return NULL;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,794评论 0 33
  • 2014年的苹果全球开发者大会(WWDC),当Craig Federighi向全世界宣布“We have new ...
    yeshenlong520阅读 2,339评论 0 9
  • 今天是给领导打伞,冒雨完成任务的宝宝 比心心❤ 好多台湾小吃,好多台湾人,但是都是陌生人好尴尬
    闫丽彬阅读 132评论 0 0
  • 一棵植物能让你联想到什么呢?绿色?生命?活力?在学校里有一抹生机勃勃的绿,能让人感觉到这里充满着活力气息,同时也对...
    7秒记忆小鱼儿阅读 1,804评论 0 1
  • 俗话说的好:“只谈情怀画大饼的老板不是好老板,真正的好boss给钱给到位,带你成长带你飞。”转眼间又到了年末,眼看...
    Vivian思朦阅读 394评论 0 0