首页 > 解决方案 > 隐藏作为实现细节的类型参数

问题描述

我有一个类,它有一些不是实现细节的类型参数,有些是。

在不使用未经检查的强制转换的情况下,处理不应成为公共 API 一部分的类型参数的最佳方法是什么?

我有一个类是由一个选择合适的助手的构建器创建的。就我而言,助手知道如何在类似缓冲区的对象之间进行批量读/写。

/**
 * @param <T> a type parameter that end users of PublicClass cannot ignore.
 * @param <X> has a specific relationship to T, but
 *     is an artifact of how PublicClass is implemented.
 */
public class PublicClass<T> {
  // This constructor is called from a builder.
  // The builder just returns
  //     new PublicClass<>(aHelper, someMutableState)
  // <X> is inferred from the choice of parameters.      
  <X> PublicClass(
      Helper<T, X> helper,
      StatefulInternalObject<T, X> someMutableState) {
    ...
  }

  ...
}

所以有一个公共类和一个公共构建器,以及一些包私有实现细节类。

我不想暴露<X>给客户,但是我的助手和我的有状态对象需要以依赖的方式进行交互<X>,并且助手将使用的类型转换为使用的<T>类型<X>,因此使用未经检查的强制转换<X>会使 PublicClass 的实现变得脆弱。

我可以创建另一个具有两组类型参数的隐藏类,然后将我的公共 API 转发到该类:

public class PublicCLass<T> {
  private final class TypedImpl<T, ?> typeSafeImplementation;

  <X> PublicClass(
      Helper<T, X> helper,
      StatefulInternalObject<T, X> someMutableState) {
    typeSafeImplementation = new TypedImpl<>(
        helper, someMutableState);
  }

  // Public API just forwards to an internal
  // implementation class.
  public SomeType0 someMethod(SomeType1 x) {
    return typeSafeImplementation(x);
  }

  ...
}

有没有更好的方法不需要这些浅层转发方法?

标签: javatype-parameterinformation-hiding

解决方案


推荐阅读