形状工厂
题目
工厂模式是一种常见的设计模式。实现一个形状工厂 ShapeFactory 来创建不同的形状类。这里我们假设只有三角形,正方形和矩形三种形状。
样例
题解
唯一需要注意的就是反斜杠\的转义问题,用“\\”表示。
/**
* 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 {
public void draw()
{
System.out.println(" ----");
System.out.println("| |");
System.out.println(" ----");
}
}
class Square implements Shape {
public void draw()
{
System.out.println(" ----");
System.out.println("| |");
System.out.println("| |");
System.out.println(" ----");
}
}
class Triangle implements Shape {
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) {
Shape shape = null;
if (shapeType.equals("Rectangle"))
{
shape = new Rectangle();
}
else if (shapeType.equals("Square"))
{
shape = new Square();
}
else if (shapeType.equals("Triangle"))
{
shape = new Triangle();
}
return shape;
}
}
Last Update 2016.9.18