我正在 Kotlin 中实现快速排序算法。为此,我创建了一个接口(interface) ISort,它带有一个类型参数和一个函数 sort。对于排序,我需要交换操作。我想知道这个交换功能的最佳位置是什么。我的想法:
1) 不幸的是,在 Kotlin 中不能保护接口(interface)函数。因此,每个类都可以在其实现中看到交换,这不太好(尽管它也不太糟糕,我同意)。
2) 把它放在 QuickSort 实现中更糟糕,因为可能有几个 ISort 接口(interface)的实现需要交换函数。
3) 我的下一个想法是创建一个单例对象,但 Kotlin 允许具有类型参数的对象。
这是接口(interface)定义:
interface ISort<T> {
fun sort(toSort: MutableList<T>): MutableList<T>
// 1) Putting swap here has a too high visibility
}
这是 QuickSort 类的框架:
class QuickSort<T> : ISort<T> {
override fun sort(toSort: MutableList<T>): MutableList<T> {
doQuickSort(toSort) // Internally uses swap
return toSort
}
// 2) Putting swap here might lead to code duplication of swap
}
因此,从软件工程的角度来看,交换操作的最佳位置/位置是什么。
最佳答案
顶级功能
在文件中 sort.kt
或者,
package abc.def.sort
fun <T> quicksort(list: MutableList<T>): MutableList<T> {
...
}
// invisible in other files, but visibie in "sort.kt"
private fun <T> swap(...) {
...
}
使用
swap
其他排序函数,您将需要在同一文件中定义其他排序函数。 (或多次复制 swap
函数。)推荐用于非常简单的功能。
对象作为命名空间
这类似于上面的方法,但比前一种方法更 OOP-ish。
object QuickSort {
fun <T> sort(list: MutableList<T>): MutableList<T> {
...
}
private fun <T> swap(...) {
...
}
}
或者
object Sorts {
fun <T> quicksort(list: MutableList<T>): MutableList<T> {
...
}
// add other sort methods...
private fun <T> swap(...) {
...
}
}
但是,在 Kotlin (Best practices for top-level declarations) 中不建议这样做。
抽象类和对象的组合
swap
可以通过这种方式将函数重用于其他类型。abstract class Sort {
abstract fun <T> sort(list: MutableList<T>): MutableList<T>
protected fun <T> swap(...) {
...
}
}
object QuickSort : Sort() {
override fun <T> sort(list: MutableList<T>): MutableList<T> {
...
}
}
我认为[制作类型参数
T
是类类型参数,而不是函数类型参数] 会使问题变得不必要地复杂,因为每次使用不同类型时都必须创建一个类实例 T
.
关于sorting - Kotlin:排序 |交换操作的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44455970/