- Shape Factory
中文English
Factory is a design pattern in common usage. Implement a ShapeFactory that can generate correct shape.
You can assume that we have only three different shapes: Triangle, Square and Rectangle.
Example
Example 1:
Input:
ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape(“Square”);
shape.draw();
Output:
| |
Example 2:
Input:
ShapeFactory sf = new ShapeFactory();
shape = sf.getShape(“Triangle”);
shape.draw();
Output:
/
/
/____
Example 3:
Input:
ShapeFactory sf = new ShapeFactory();
shape = sf.getShape(“Rectangle”);
shape.draw();
Output:
解法1:
注意:
- \的使用。因为\是转义字符。
代码如下:
/**
* 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 {
void draw() const {
cout<<" ----"<<endl;
cout<<"| |"<<endl;
cout<<" ----"<<endl;
}
};
class Square: public Shape {
void draw() const {
cout<<" ----"<<endl;
cout<<"| |"<<endl;
cout<<"| |"<<endl;
cout<<" ----"<<endl;
}
};
class Triangle: public Shape {
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 == "Triangle") {
return new Triangle();
} else if (shapeType == "Rectangle") {
return new Rectangle();
} else if (shapeType == "Square") {
return new Square();
} else {
return NULL;
}
}
};