[LintCode] Shape Factory 形狀工廠


 

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

 

 You can assume that we have only tree different shapes: Triangle, Square and Rectangle.

 

 Example

 ShapeFactory sf = new ShapeFactory();

 Shape shape = sf.getShape("Square");

 shape.draw();

 >>  ----

 >> |    |

 >> |    |

 >>  ----

 

 shape = sf.getShape("Triangle");

 shape.draw();

 >>   /\

 >>  /  \

 >> /____\

 

 shape = sf.getShape("Rectangle");

 shape.draw();

 

這道題讓我們求形狀工廠,實際上就是Factory pattern的一個典型應用,說得是有一個基類Shape,然后派生出矩形,正方形,和三角形類,每個派生類都有一個draw,重寫基類中的draw,然后分別畫出派生類中的各自的形狀,然后在格式工廠類中提供一個派生類的字符串,然后可以新建對應的派生類的實例,沒啥難度,就是考察基本的知識。

 

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

class Rectangle: public Shape {
public:
    void draw() const {
        cout << " ---- " << endl;
        cout << "|    |" << endl;
        cout << " ---- " << endl;
    }
};

class Square: public Shape {
public:
    void draw() const {
        cout << " ---- " << endl;
        cout << "|    |" << endl;
        cout << "|    |" << endl;
        cout << " ---- " << endl;
    }
};

class Triangle: public Shape {
public:
    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) {
        if (shapeType == "Square") return new Square();
        else if (shapeType == "Triangle") return new Triangle();
        else if (shapeType == "Rectangle") return new Rectangle();
        else return NULL;
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM