考虑一下守则:
/**
* For a given interface, return a default implementation
*/
public class ImplementationFactory<T>
{
public static void main(String[] args)
{
AddressBookUI ui = ImplementationFactory.getImpl(AddressBookUI.class);
}
public static <T extends BasicUI> T getImpl(Class<T> uiClass)
{
if (uiClass.equals(AddressBookUI.class))
{
/*
* Compile error if cast is removed.
* Casting to T leaves an unchecked cast warning.
*/
return (T) new AddressBookFrame();
}
// a bunch more else-if checks would be here
return null;
}
}
// These are defined elsewhere:
interface BasicUI {}
interface AddressBookUI extends BasicUI {}
interface StockQuoteUI extends BasicUI {}
class AddressBookFrame implements AddressBookUI {}
class StockQuoteFrame implements StockQuoteUI {}为什么getImpl()中的强制转换首先是必需的?有什么更好的办法吗?
另外,我尝试在getImpl()中创建一个Map,而不是在()中使用链式if-else检查:
private static Map<Class<? extends BasicUI>, Class<? extends BasicUI>> map;然后,我将对映射的值调用newInstance(),但问题是:
理想情况下,地图应该是
但我不知道怎么做。
编辑:将BasicUI的另一个实现添加到代码中
发布于 2013-03-26 19:09:56
需要强制转换,因为在编译时,无法判断AddressBookFrame是T的一个实例。
若要避免警告,请在运行时检查类型:
return uiClass.cast(new AddressBookFrame());这样做,您的地图实现将工作,并将类型安全。
https://stackoverflow.com/questions/15645327
复制相似问题