题目
工厂模式是一种常见的设计模式。实现一个形状工厂 ShapeFactory
来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。
样例
ShapeFactory sf = new ShapeFactory();
Shape shape = sf.getShape("Square");
shape.draw();
>> ----
>> | |
>> | |
>> ----
shape = sf.getShape("Triangle");
shape.draw();
>> /\
>> / \
>> /____\
shape = sf.getShape("Rectangle");
shape.draw();
>> ----
>> | |
>> ----
代码
/**
* Your object will be instantiated and called as such:
* ShapeFactory sf = new ShapeFactory();
* Shape shape = sf.getShape(shapeType);
* shape.draw();
*/
interface Shape {
void draw();
}
class Rectangle implements Shape {
// Write your code here
public void draw() {
System.out.println(" ---- ");
System.out.println("| |");
System.out.println(" ---- ");
}
}
class Square implements Shape {
// Write your code here
public void draw() {
System.out.println(" ---- ");
System.out.println("| |");
System.out.println("| |");
System.out.println(" ---- ");
}
}
class Triangle implements Shape {
// Write your code here
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
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("Triangle")) {
return new Triangle();
} else if(shapeType.equalsIgnoreCase("Rectangle")) {
return new Rectangle();
} else if(shapeType.equalsIgnoreCase("Square")) {
return new Square();
}
return null;
}
}