首页 > 解决方案 > 了解“编码到接口”以隐藏实现细节

问题描述

我正在学习“对接口进行编码以隐藏实现细节”的设计原则,我对这个想法感到困惑。在我的示例中,我有一个包含 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.
     }
}

标签: javainterfacesoftware-design

解决方案


这个想法是返回一个尽可能通用但足够具体的类型。

例如,返回 aLinkedList可能过于具体 - 如果客户端开始使用该方法,而您后来出于性能原因getFirst决定返回 a ,则客户端代码将中断。ArrayList因此返回更通用类型的原则,例如 a List

您甚至可以更通用并返回 a Collection- 例如,如果您认为客户端代码不需要访问集合中的第 n 个位置,这可能是有意义的。但是,如果您认为routine.get(n-1)无需迭代即可访问例程Collection的第 n 步(


推荐阅读