题目描述:
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: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();
>> ----
>> | |
>> ----
就是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;
}
}
};