   [java] Object Factorys in Java ?
  Hey, here I go again...In C++ Object Factorys are very simple to implement.I have a Factory class, where I a couple of static functions:RegisterObject(...), UnregisterObject(...) etc...This is very good for "pluggable design", where you simply can add files to your project without having to modify old files.So, what I want to do is something like this:   //I want to do this in the SAME file...public class MyNewShapeType {//...}//Now I create a Functor that returns a new MyNewShapeType:JCFunctor MyNewShapeCreateFn = new JCFunctor() {public MyNewShapeType execute() {return (new MyNewShapeType)}}//Register the object at my shapefactory:boolean bRegistered = MyShapeFactory.RegisterObject("MyNewShape", MyNewShapeCreateFn);That is somewhat how I would do it in C++, now in java everything needs to be put in a class, so I thought this should work:   public class MyNewShapeType {//Now I create a Functor that returns a new MyNewShapeType:public static JCFunctor MyNewShapeCreateFn = new JCFunctor() {public MyNewShapeType execute() {return (new MyNewShapeType)}}//Register the object at my shapefactory:public static boolean bRegistered = MyShapeFactory.RegisterObject("MyNewShape", MyNewShapeCreateFn);}I thought that since the Functor object is static, that object should be created before I create any MyNewShapeType, so the static JCFunctor should be created with once at runtime right?And the same with the boolean bRegistered, since that is also static it should be initialized with whatever the MyShapeFactory.RegisterObject() returns - which in turn also is static and in addition registers an object!But this never happens, not until I manually create an object of MyNewShapeType type - which would mean that the static types in the MyNewShapeType class are NOT initialized until I create an object of MyNewShapeType!But the bRegistered and JCFunctor MyNewShapeCreateFn CAN be used without creating a MyNewShapeType object first...So is there any static initializing or something that needs to be done??would appreciate an explanation on how this works in java...thank you! 
  Hum, after some research I found out that statics are initialized the first time the class containing them is used I also realize that it is the "Java automatically loading class system" that is the problem here... since even if i import a class, it will not be included in the code unless that class is used - which is very good, BUT not in this case But I can't believe that it would end here?? The MUST be a way of doing this right?Maybe if there was an option to FORCE a class to be included in the project or something... so that the statics would be initialized without having to use the class before...What I mean is that style like this is quite essential in making a program easy to maintain and expandable - especially a game, where you don't want to search for the code where you initialize the objectfactory for Monster types, but rather only want to adda a new file for each Monster type you want your factory to be able to produce...I mean... someone gotta know thx!   [edited by - FxMazter on February 10, 2004 7:48:15 PM] [edited by - FxMazter on February 10, 2004 7:54:52 PM];  You don''t need all of that trickery with Java. Let''s say you want to define an interface for (for argument''s sake) a car. All cars must implement this interface. At runtime, you want to be able to add any type of Car implementation to the app, regardless of whether it is a built-in implementation or an addon.You take a CarFactory class, register a fully qualified java class name with it ("com.mydomain.mypackage.MyCar"), then the CarFactory returns an instance of MyCar by 1) instantiating it via Class.newInstance and 2) verifying that the instantiated object implements the car interface. String className = "com.mydomain.mypackage.MyCar";Class clazz = Class.forName(className);Class[] ifaces = clazz.getInterfaces();for(int i=0; i<ifaces.length; ++i)   if("com.mydomain.mypackage.Car".equals(ifaces[i])) return (Car)clazz.newInstance();That''s the long, convoluted way to do it. You could probably get away with something like this: Object obj = Class.forName(className).newInstance();if(obj instanceof Car)   return (Car)obj;Either way, this will all have to be wrapped in a try with (preferably) multiple catches, as there are 3 or 4 potential exceptions. Unless I entirely misunderstodd what you''re trying to do, this should do the trick for you. Get your head out of C++ mode when coding Java! ;  Here is a piece of code to FORCE a class to be loaded in to the VM at run time.  This might be of help.  I could see you using it to look for class files the match a certain signature like *Factory.class This would be done in the base class.  I hope it helps.  Although I admit that, it is a bit of a hack.import java.io.*;import java.net.*;import java.util.*;public class Factory{static Vector vec = new Vector();public static void main(String[] args){// Create a File object.File file = new File("");    try {// Convert File to a URLURL url = file.toURL();URL[] urls = new URL[]{url};    // Create a new class loader with the directoryClassLoader cl = new URLClassLoader(urls);   //load the new classClass cls = cl.loadClass("myNew"+Factory.class.getName());//create an instance of the classcls.newInstance();} catch (Exception e) {e.printStackTrace();}//just to show that we have loaded the child class at this pointEnumeration e = vec.elements();while(e.hasMoreElements()){System.out.println(e.nextElement());}}}  public class myNewFactory{protected myNewFactory(){Factory.vec.add(this);}} ;  Thank you, indeed that would work. But still that is not an ídeal way of achieving my goal :/, but still it would work I have also been thinking to let each factory have a corresponding file with a class like "RegisterXXXFactoryTypes" where I put the registration of any new types. The Factory would make an instance of this class, and thus registrate the new types...Anyway - conclusion:With your method: I would need to put all the factory classes in the same folder, since it would be inconvenient adding new directorys to be read from. Each factory file name would need to end in a similar fashin, eg "Factory" or something, which is no problem at all. With your sollution I don''t need to edit old factory files what so ever - I just add files for new types, so the goal will be achieved to 100% With my method: I don''t need to do any "hacking", and the files can be called whatever I want. But, each time I want to add a new type to the factory, I will have to edit the "RegisterXXXFactoryTypes" file to register a new type, which misses the goal of mine - no need for reedit files when adding a new type.I think I''ll try that method of yours, thoug I must admint that I''m not 100% fond of it Thank you!;  A good Factory example is contained within the book "Thinking in Patterns" by Bruce Eckel (search google for "thinking in patterns" and follow the first link).It has even java code inside.   [edited by - Petr Stedry on February 11, 2004 7:08:25 AM];  Thank you guys!Petr : I''ll check that out, thxAldacron: thank you, your example combined with Egroths, would do the trick I want ;  I already solved the problem, thank you guys! 