1

我有很多围绕服务的代理类,而且看起来(几乎)都一样。我可以通过使用将and类作为类型参数的泛型单例类以某种方式减少代码重复吗?ServicePort

这是我想要开始的完全错误的代码:

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(),我该怎么写?
4

2 回答 2

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;
    }
}
于 2013-09-12T09:29:13.260 回答
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

于 2013-09-12T10:04:46.823 回答