62,614
社区成员
发帖
与我相关
我的任务
分享
public abstract class Shape
{
abstract void draw();
}
public class Circle extends Shape
{
@Override
public void draw()
{
System.out.println("draw a circle!");
}
}
public class Line extends Shape
{
@Override
public void draw()
{
System.out.println("draw a line!");
}
}
public class Rectangle extends Shape
{
@Override
public void draw()
{
System.out.println("draw a Rectangle!");
}
}
import java.util.HashMap;
import java.util.Map;
public class ShapeFactory
{
public static final int SHAPE_TYPE_CIRCLE=1;
public static final int SHAPE_TYPE_RECTANGLE=2;
public static final int SHAPE_TYPE_LINE=3;
private static Map<Integer,String> shapes=new HashMap<Integer,String>();
static
{
shapes.put(new Integer(SHAPE_TYPE_CIRCLE),"Circle");
shapes.put(new Integer(SHAPE_TYPE_RECTANGLE),"Rectangle");
shapes.put(new Integer(SHAPE_TYPE_LINE),"Line");
}
public static Shape getShape (int type)
{
try
{
String className=shapes.get(new Integer(type));
return (Shape) Class.forName(className).newInstance();
}
catch(Exception e)
{
return null;
}
}
}
import java.io.*;
public class Panel
{
public void selectShape() throws Exception
{
System.out.println("请输入形状类型:");
BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
int shapeType=Integer.parseInt(input.readLine());
Shape shape=ShapeFactory.getShape(shapeType);
if(shape==null)
System.out.println("输入的形状的不存在!");
else
shape.draw();
}
public static void main(String[] args) throws Exception
{
new Panel().selectShape();
}
}