java - 了解“编码到接口”以隐藏实现细节
问题描述
我正在学习“对接口进行编码以隐藏实现细节”的设计原则,我对这个想法感到困惑。在我的示例中,我有一个包含 RoutineStep 列表的 WorkoutRoutine 类。通过遵循接口原则的编码,我的getWorkoutRoutine()方法将返回List接口,从而对客户端隐藏了使用哪个列表的实现细节。
如果我决定将实现从 RoutineStep 的 List 更改为 RoutineStep 的数组,将不会向客户端披露返回类型,因为 List 会向客户端显示已实现的列表而不是数组、树、图形或任何其他数据结构体?我怎样才能最好地封装我的数据结构来保存一个 RoutineStep 的集合,这样如果 List 更改为数组、树、图形等,我可以在不破坏客户端代码的情况下更改数据结构的实现?
public class WorkoutRoutine {
private List<RoutineStep> workoutRoutine;
public List<RoutineStep> getWorkoutRoutine() {
//What if I later decide to change the data structure from a List to an array, tree,
//graph, set, map. What approach should I take so that the client code doesn't break
//as they would have already coded to receive a List but after changing the
//implementation from a list to an array or any other data structure, their code would
//break.
}
}
解决方案
这个想法是返回一个尽可能通用但足够具体的类型。
例如,返回 aLinkedList
可能过于具体 - 如果客户端开始使用该方法,而您后来出于性能原因getFirst
决定返回 a ,则客户端代码将中断。ArrayList
因此返回更通用类型的原则,例如 a List
。
您甚至可以更通用并返回 a Collection
- 例如,如果您认为客户端代码不需要访问集合中的第 n 个位置,这可能是有意义的。但是,如果您认为routine.get(n-1)
无需迭代即可访问例程Collection
的第 n 步(
推荐阅读
- r - R:ggarrange()“没有要重播的图形”错误
- 3dsmax - HDRi 环境和移动摄像机
- python - 具有自定义模型的自定义拥抱脸标记器
- laravel - Laravel Blade 如何不在表格中显示重复值
- kotlin - 协程 Kotlin
- jboss - 如何修改 Keycloak 使用的上下文路径
- python-3.x - 如何在图表中显示直径?
- react-native - ola uber 类型带有 react native 的可拖动地图
- reactjs - Redux 工具包 - 如何在表单提交流程后重定向?
- node.js - Nodejs 休息端点作为 kafka 生产者 - 性能缓慢