我有很多围绕服务的代理类,所有看起来(几乎)都是一样的。我可以使用泛型单例类以某种方式减少代码重复,将Service
和Port
类作为类型参数?
这是我想要开始的完全错误的代码:
public class MyProxy<S extends Service, P extends BindingProvider>
{
private static final MyProxy<S extends Service, P extends BindingProvider> instance
= new Proxy<S extends Service, P extends BindingProvider>();
private S service;
public static MyProxy<S extends Service, P extends BindingProvider> getInstance() {
return instance;
}
}
MyProxy
的类型参数我认为是正确的。instance
单身成员变量,以及如何?service
应该更容易,我可以将类型参数作为成员吗?getInstance()
的返回类型怎么样,怎么写呢?答案 0 :(得分:0)
这是与我的第一条评论相对应的代码。正如我所说,这涉及未经检查的演员表。
public static class MyProxy<S extends Service, P extends BindingProvider> {
private static final MyProxy<? extends Service, ? extends BindingProvider> instance = new Proxy<Service, BindingProvider>();
private S service;
public static <S extends Service, P extends BindingProvider> MyProxy<S, P> getInstance() {
return (MyProxy<S, P>) instance;
}
}
答案 1 :(得分:0)
以下是具有单个类型参数的此类代理框架的示例:
public class MyProxy<S extends Service> {
private static final ConcurrentHashMap<Class<?>, MyProxy<?>> INSTANCES
= new ConcurrentHashMap<>();
private S service;// could be final depending on your demands
private final Class<S> type;
MyProxy(Class<S> serviceType, S serviceInstance) {
service=serviceInstance;
type=serviceType;
}
/**
* Helper method for a runtime cast.
*/
@SuppressWarnings("unchecked")
public <S extends Service> MyProxy<S> cast(Class<S> serviceType) {
if(serviceType!=type) throw new ClassCastException(type+" != "+serviceType);
return (MyProxy<S>)this;
}
/**
* Get the proxy for type {@code sType}.
*/
public static <S extends Service> MyProxy<S> getInstance(Class<S> sType) {
MyProxy<?> old=INSTANCES.get(sType);
if(old!=null) return old.cast(sType);
MyProxy<S> proxy=allocateNewProxy(sType);
old=INSTANCES.putIfAbsent(sType, proxy);
return old==null? proxy: old.cast(sType);
}
}
所以你可以用以下方式使用它:
MyProxy<A> proxyA=MyProxy.getInstance(A.class);
假设A是Service