题目地址:
https://www.lintcode.com/problem/shape-factory/description
要求设计一个工厂类,可以根据输入返回对应的形状的对象。
代码如下:
interface Shape {
void draw();
}
class Rectangle implements Shape {
// Write your code here
@Override
public void draw() {
System.out.println(" ----");
System.out.println("| |");
System.out.println(" ----");
}
}
class Square implements Shape {
// Write your code here
@Override
public void draw() {
System.out.println("---- ");
System.out.println("| |");
System.out.println("| |");
System.out.println(" ---- ");
}
}
class Triangle implements Shape {
// Write your code here
@Override
public void draw() {
System.out.println(" /\\");
System.out.println(" / \\");
System.out.println("/____\\");
}
}
public class ShapeFactory {
/**
* @param shapeType a string
* @return Get object of type Shape
*/
public Shape getShape(String shapeType) {
// Write your code here
switch (shapeType) {
case "Rectangle": return new Rectangle();
case "Square": return new Square();
case "Triangle": return new Triangle();
default: return null;
}
}
}
时空复杂度 O ( 1 ) O(1) O(1)。