2015-10-17 28 views
0

假设我有一个函数有整型参数(id)和函数里面我想创建一个与(id)关联的类的对象,我不喜欢使用(if else)语句,这可以如何实现。我怎样才能映射唯一的数字和类在android

请注意,我不能使用类名作为函数的参数,因为我使用Proguard。

回答

0

在你的情况,你可以尝试这样的事:

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(); 
    } 
} 

核心是Map<Integer, /*something*/>而不是switch

+0

但是,如果类的构造函数有输入参数呢? –

+0

@MHDShaker可能通过将它们添加到'make()'方法 – zapl