简体   繁体   中英

How can I map between unique numbers and classes in android

Let's say I have a function has integer parameter (id) and inside the function I would like to create an object of class associated with the (id), I don't like to use (if else) statements, How this can be achieved.

Note, I can't use class name as function's parameter because I use Proguard.

In your case, you could try something like this:

interface Factory {
    Object make();
}

class Foo {
}

class Bar {
}

public static void main(String... args) {
    Map<Integer, Factory> mapping = new HashMap<>();
    mapping.put(42, new Factory() {
        @Override
        public Object make() {
            return new Foo();
        }
    });
    mapping.put(9001, new Factory() {
        @Override
        public Object make() {
            return new Bar();
        }
    });

    int someNumber = (int) (Math.random() * 10000);
    Factory factory = mapping.get(someNumber);
    Object result;
    if (factory != null) {
        result = factory.make();
    }
}

The core is a Map<Integer, /*something*/> instead of a switch .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM