题目: 实现一个画板,根据选择,画出不同形状的图形。
自己写的: 1.Shape:
package demo.panel;public abstract class Shape { protected abstract void draw();}
2.圆,正方形
package demo.panel;public class Circle extends Shape{ @Override protected void draw() { System.out.println("now draw a circle!"); }}package demo.panel;public class Rectangle extends Shape { @Override protected void draw() { System.out.println("now draw a rectangle"); }}
实现: 我的:
package demo.panel;import java.io.BufferedReader;import java.io.InputStreamReader;public class Panel { public void selectShape(int shape){ Shape sh=null; switch (shape) { case 0: sh = new Circle(); break; case 1: sh = new Rectangle(); default: break; } if(sh==null){ System.out.println("your input shaple is not find!"); }else{ sh.draw(); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int shapeType = Integer.parseInt(br.readLine()); Panel panel = new Panel(); panel.selectShape(shapeType); } }
别人的写法: 把selectShape里面独立一个工厂模式,产生图形:
package demo.panel;import java.util.HashMap;import java.util.Map;public class ShapeFactory { public static final int SHAPE_CIRCLE = 0; public static final int SHAPE_RECTANGLE = 1; public static MapshapeMap = new HashMap (); static{ shapeMap.put(new Integer(SHAPE_CIRCLE), "Circle"); shapeMap.put(new Integer(SHAPE_RECTANGLE), "Rectangle"); } public static Shape getShape(int shapeType){ String className = shapeMap.get(new Integer(shapeType)); if(className==null) return null; try { return (Shape)Class.forName(className).newInstance(); } catch (Exception e) { return null; } }}package demo.panel;import java.io.BufferedReader;import java.io.InputStreamReader;public class Panel { public void selectShape(int shape){ Shape sh=ShapeFactory.getShape(shape); if(sh==null){ System.out.println("your input shaple is not find!"); }else{ sh.draw(); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int shapeType = Integer.parseInt(br.readLine()); Panel panel = new Panel(); panel.selectShape(shapeType); }}耦合性最好的:把图形放到配置文件中配置文件:0=Circle 1=Rectangle