Kotlin:排序| 交换操作的位置

我在Kotlin中实现了Quicksort算法。 为此,我使用types参数和单个函数( sort)创建了一个接口ISort 。 为了排序,我需要交换操作。 我想知道这个交换function的最佳位置是什么。 我的想法:

1)不幸的是,在Kotlin中,不能使接口function得到保护。 因此,每个class级都可以在其实施中看到交换,这并不太好(尽管也不算太差,我同意)。

2)把它放在QuickSort实现中更糟,因为可能有几个需要交换function的ISort接口的实现。

3)我的下一个想法是创建一个单例对象,但Kotlin允许具有types参数的对象。

这里是接口定义:

interface ISort { fun sort(toSort: MutableList): MutableList // 1) Putting swap here has a too high visibility } 

这里是QuickSort类的框架:

 class QuickSort : ISort { override fun sort(toSort: MutableList): MutableList { doQuickSort(toSort) // Internally uses swap return toSort } // 2) Putting swap here might lead to code duplication of swap } 

所以,从软件工程的角度来看,交换操作的最佳位置是什么。

顶级function

在一个文件sort.kt左右,

 package abc.def.sort fun  quicksort(list: MutableList): MutableList { ... } // invisible in other files, but visibie in "sort.kt" private fun  swap(...) { ... } 

要使用其他types的swapfunction,您需要在同一个文件中定义其他排序function。 (或多次复制swapfunction。)

这被推荐用于非常简单的function。

对象作为命名空间

这与上面的方法类似,但是比以前的方法更多的OOP。

 object QuickSort { fun  sort(list: MutableList): MutableList { ... } private fun  swap(...) { ... } } 

要么

 object Sorts { fun  quicksort(list: MutableList): MutableList { ... } // add other sort methods... private fun  swap(...) { ... } } 

但是,在Kotlin( 顶层声明的最佳实践 )中不推荐这样做。

抽象类与对象的结合

swapfunction可以以这种方式重新用于其他种类。

 abstract class Sort { abstract fun  sort(list: MutableList): MutableList protected fun  swap(...) { ... } } object QuickSort : Sort() { override fun  sort(list: MutableList): MutableList { ... } } 

我认为[使types参数T是类types参数,而不是函数types参数]将使问题不必要地更复杂,因为每次使用不同的typesT时都必须创建一个类实例。