java-john wrote:
> I have a class that uses composition of interfaces. I want to be able
> to allow users to decide at run-time which implementations of these
> interfaces to instantiate. What is the best way to do this? Are there
> any frameworks out there? Is there some design pattern for this?
>
> For example:
>
> public interface MyInterface {
> public String getValue();
> }
>
> public class MyClass {
> private MyInterface myInterface;
> public MyClass() {
> myInterface = new SomeRunTimeImplementationOfMyInterface();
> }
> }
>
This usually depends on your product's configuration, which in turn
usually depends on the user's choice of product options either when the
software is run, or on the options-window during execution.
This will usually involve the software's reading a file of options when
it's started, and there are innumerable ways of doing this: Properties,
Preferences, a roll-your-XML file, etc. (Even good-ol' command-line
parameters, though not recommended.)
The point is that, whatever means is used to input these options to the
software, somewhere in the code there will be decision points based on them.
A very basic example, if you have your configuration file as a text file
specifying whether to display graphics on the user screen or not, the
configuration file might be as simple as:
graphics=off
And the code will be something like:
Class Start {
void readConfiguraionFile() {
Properties properties = new Properties();
try {
properties.load(new
FileInputStream("filename.properties"));
} catch (IOException e) {
}
String graphicsOption = properties.getProperty("graphics");
GraphicsFacade graphics = null;
if (graphicsOptions.equals("on")) {
graphics = new FullGraphicsDisplay();
} else {
graphics = new TextOnlyDisplay();
}
store(graphics);
}
}
Class SomethingElse {
void welcomeScreen() {
GraphicsFacade graphics = retrieveGraphics();
graphics.showUserWelcome();
}
}
--
www.EdmundKirwan.com - Home of The Fractal Class Composition.
Download Fractality, free Java code analyzer:
http://www.EdmundKirwan.com/servlet/...c-page130.html