问题
Say I have a Java interface Blender.java
with various implementations Cuisinart.java
, Oster.java
, Blendtec.java
, etc. Now I want to write a program like so:
public class Blendifier {
// ...
public static void main(String... args) {
Blender blender = new Cuisinart();
blender.blend();
}
}
But now if I want to use the Blendtec
instead of the Cuisinart
, I have to open up the source, change the code, and recompile.
Instead, I'd like to be able to specify which Blender
to use on the fly when I run the program, by writing the class name I want as a command line argument.
But how can I go from a String containing the name of a class, to constructing an actual instance of that class?
回答1:
If you don't want to go through the trouble that is Java reflection, you can write a simple static factory method that takes a String and returns the appropriate object.
public static Blender createBlender(String type){
switch(type){
case "Cuisinart": return new Cuisinart();
case "Oster": return new Oster();
//etc
}
}
Then you just pass in your command line argument into it and you'll have whatever Blender you need.
The only possible design issue is that you would have to type out a line for every class that implements Blender, so you'd have to update the method if you added more types later.
回答2:
You have a few ways to accomplish that:
e.g. if-else construct
Blender blender = null;
if (args[0].equals("Cuisinart")) {
blender = new Cuisinart();
} else if (...)
where args[0] is your first command line argument.
来源:https://stackoverflow.com/questions/23207000/specify-which-implementation-of-java-interface-to-use-in-command-line-argument