Java – how to allow users to select classes to initialize
•
Java
I have an abstract class foo, which contains a function a (object o)
I hope the users of the program can determine the implementation using foo (for example, afoo, bfoo, cfoo, etc.), but I want to reduce the use of conditional logic so that I can add it to my future plan more safely
I currently have an enum Ebar that contains the names of all foo implementations that users can choose, but I'm not sure how to use it to initialize this class
Solution
Store the foo instance to be used in each enumerated instance, or add a method to create foo:
public enum FooType { A { @Override public Foo createFoo() { return new AFoo(); } },B { @Override public Foo createFoo() { return new BFoo(); } } public abstract Foo createFoo(); }
Then, once the user selects the type, all you need to do is
selectedFooType.createFoo().a(object);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码