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; } };