I’m developing an application that should use different class types based on a single piece of information. To better illustrate my question, let me give an example:
suppose INFO is a boolean value. Based on its value, my code must use either instances of some class A, or some class B. Note that for every A, B is its subclass. INFO is set when the application starts and it’s not changed throughout the app lifecycle.
My question: what’s the most optimal way to implement this?
Here are some approaches I’ve come up with, but feel free to suggest others:
1. Factory class with methods:
public static A getA(final boolean INFO) {
return INFO ? new A() : new B();
}
2. Wrapper classes:
class WrapperForSomeClass {
public final A instance;
public WrapperForSomeClass(final boolean INFO) {
instance = INFO ? new A() : new B();
}
}
3. Interface + Factory class:
public interface IWrappable<T> {
T get(final boolean INFO);
}
private static final IWrappable<A> WRAPPER_FOR_A = new IWrappable<A>() {
public A get(final boolean INFO) {
return INFO ? new A() : new B();
}
};
public static A getA(final boolean INFO) {
return WRAPPER_FOR_A.get(INFO);
}
If I had to choose, I’d go with no.3. What say ye?
1 is shortest and cleanest. Place this method into A class, in order not to create redundant factory class.
Why you’d go for 3? It does the same, but with a lot more code.