ShapeFactory.javaimport 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; }
  }
}
Panel.java
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();
  }
}
为何我输入1或2或3都提示该形状不存在?看了好久也看不出来啊!!

解决方案 »

  1.   

    你要返回的是Circle等类的对象,但是实例化的时候没找到这个类,所以返回的是一个null对象.你当前路径下没有Circle这些类的定义,如果在其它包中,要指定正确的包名.而且你在异常捕获的时候什么都没做,所以没看出发生了异常.你可以在catch块中打印一下堆栈信息(e.printStackStrace();)输出的应该是ClassNotFoundException
      

  2.   

    确实如imA(男的不会,会的不男) ( ) 信誉:5   所说,还有4个文件没通过编译,因为没有包含它们,所以也没通过编译,然后把这些文件全放到ShapeFoctory.java 中就可以了:
    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; }
      }
    }abstract class Shape {
      abstract void draw();
     }class Circle extends Shape {
      public void draw() {
        System.out.println("draw a circle");
      }
    }class Line extends Shape {
      public void draw() {
        System.out.println("draw a line");
      }
    }class Rectangle extends Shape {
      public void draw() {
        System.out.println("draw a rectangle");
      }
    }