java - 隐藏作为实现细节的类型参数
问题描述
我有一个类,它有一些不是实现细节的类型参数,有些是。
在不使用未经检查的强制转换的情况下,处理不应成为公共 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);
}
...
}
有没有更好的方法不需要这些浅层转发方法?
解决方案
推荐阅读
- django - 带有 Axios 的 Django 和 Vue.js:发布请求时出现 500 内部服务器错误
- r - 在R中的所有列名中替换多个句点
- python - 验证两个包含浮点数和 NaN 的大型 DataFrame 是否相等的最有效方法?
- html - 如何获取受密码保护的网站的源代码?
- asp.net-core-webapi - 如果从 Visual Studio 2019 发布且中间没有 API Mgmt,如何让 Azure API 应用程序正常工作?
- azure - Azure 表存储:如何以可靠的方式保存相同数据的多个副本
- oracle - Oracle Internet Directory 12.2.1.3.0 oid_setup 命令错误
- amazon-web-services - AWS Batch 输出到 Step Functions
- python-3.x - 为 Pandas 中的缺失值估算组平均值
- mysql - 如何回填 MySQL 中的列?