// Singleton class that keeps a list of the names of different SpaceObject // classes, e.g., sun, ship, missile... // // The non-abstract SpaceObject classes should include a declaration like // the following: // // static String className = SpaceObjectRegistry.add("sun", new SpaceSun()); // // SpaceObject subtypes whose objects require initialization must define // a static member function to (1) allocate an instance, (2) do the required // initialization, and (3) pass class's identifying name and the instance to // SpaceObjectRegistry.add(). package SpaceWar; import java.awt.*; import java.awt.geom.*; import java.util.*; import java.util.Dictionary; class SpaceObjectRegistry { static Hashtable registry; // Initialize the registry, if it has not already been initialized. private static void initialize() { if (registry == null) { registry = new Hashtable(); } } // Add a SpaceObject to the registry. Returns null if the // registry already contains a SpaceObject of that name, and // leaves the old object in the registry. public static void put(String name, SpaceObject obj) { SpaceObjectRegistry.initialize(); if (registry.containsKey(name)) { return; } registry.put(name, obj); return; } // Return an enumeration of the currently-registered SpaceObject // names. public static Enumeration names() { SpaceObjectRegistry.initialize(); return (registry.keys()); } // Return a new uninitialized SpaceObject of the type corresponding // to the specified name. Return null if there is no object of the // specified name. static SpaceObject clone(String name) { SpaceObject so; SpaceObjectRegistry.initialize(); so = (SpaceObject)registry.get(name); if (so == null) { return (null); } so = so.cloneMe(); return (so); } // Return a new initialized SpaceObject of the type corresponding // to the specified name. Return null if there is no object of the // specified name. static SpaceObject clone(String name, int x, int y, double initialAngle, Color initialBodyColor, Color initialTrimColor) { SpaceObject so; so = clone(name); if (so == null) { return (null); } so.setPosition(new Point2D.Double((double)x, (double)y)); so.setAngle(initialAngle); so.setBodyColor(initialBodyColor); so.setTrimColor(initialTrimColor); return (so); } // Clone the named object in the registry. Java will throw an // exception if the object is not a ControlledSpaceObject. Return // null if there is no object of the specified name. static ControlledObject cloneControlled(String name) { return ((ControlledObject)SpaceObjectRegistry.clone(name)); } // Disable creation of SpaceObjectRegistry objects. private SpaceObjectRegistry() { } }