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