Search code examples
javaobjectrefactoringcreation

switch object creation refactor


Suppose I have classes A,B that each of them extends some class X. And I want a method to create A or B based on some parameter value(value is a result of some other logic).

Can I do it without a switch statement?

i.e.:

class X {...}
class A extends X {...}
class B extends X {...}

So naive would be to make a class:

class Z {
    X createObject(int type) {
        switch(type)
            case 1: return new A();
            ...
            case 2: return new B();
}

Solution

  • Yes, you can do it without a switch statement. I suggest using either an array or Map and Supplier.

    Map<Integer, Supplier<X>> map = new HashMap<>();
    map.put(1, A::new); // () -> new A()
    map.put(2, B::new); // () -> new B()
    
    X createObject(int type) {
        Supplier<X> supplier = map.get(type);
        if (supplier == null) return null;
        return supplier.get();
    }