001package factory.shape5;
002import java.util.List;
003import java.util.ArrayList;
004public class ShapeFactory {
005        private ShapeFactory() {}
006        static private List<Pair> pairs;
007        static private class Pair {
008                String shapename;
009                Class<?> classname;
010                Pair(String shapename, Class<?> classname) {
011                        this.shapename = shapename;
012                        this.classname = classname;
013                }
014        }
015        static public void addShape(String shapename, String classpath)
016                        throws ClassNotFoundException
017        {
018                pairs.add(new Pair(shapename, Class.forName(classpath)));
019        }
020
021        static public Shape newShape(String selector) {
022                try {
023                        for (Pair p : pairs) {
024                                if (p.shapename.equals(selector))
025                                        return (Shape) p.classname.newInstance();
026                        }
027                } catch (InstantiationException e) {
028                        throw new IllegalArgumentException();
029                } catch (IllegalAccessException e) {
030                        throw new IllegalArgumentException();
031                }
032                throw new IllegalArgumentException();
033        }
034        static { // initializer
035                pairs = new ArrayList<Pair>();
036                try {
037                        addShape("Ellipse",   "shape.s5.Ellipse");
038                        addShape("Rectangle", "shape.s5.Rectangle");
039                        addShape("Circle",    "shape.s5.Ellipse");
040                        addShape("Square",    "shape.s5.Rectangle");
041                } catch (ClassNotFoundException e) {
042                        throw new RuntimeException();
043                }
044        }
045}