adding new feature without recompiling
i have a question
i have this program in java that translates one language to another now i want to be able to add another translator later if i required at runtime without recompiling the whole thing.that is i should have the provision of adding new translators feature which i dont know now about, later without compiling.
if anybody could guide me i will really appreciate that
thanks
A factory might do the job if you've organized your existing code properly.
Assume an interface exists:public interface Translator {
public String translate(String text);
}
Also suppose you already have a single translator:package my.package;
public class EnglishToDutchTranslator implements Translator {
...
public String translate(String text) {
...
return translation;
}
}
Store this fact in a .properties file or preferences or whereever:
ENDU= my.package.EnglishToDutchTranslator
Here's the factory:public final class TranslatorFactory {
// contains the above name -> tranlator class name mappings
private static Properties translators;
// don't instantiate this class
private TranslatorFactory() { }
//
public static Translator getTranslator(String name) {
String clazz= translators.getProperty(name);
if (clazz == null) return null;
try {
return (Translator)Class.forName(clazz).newInstance();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
Basically all the factory does is 1) get the fully qualified class name
given the name of the translator and 2) instantiate an object from that
class. All that it cares about is that the object implements the Translator
interface. You can build new translators and register them in that
properties file. A caller should get a translator as follows:Translater t= TranslatorFactory.getTranslator("ENDU");
kind regards,
Jos
JosAHa at 2007-7-14 22:40:29 >
