能用好类与接口的话,代码的复用率会非常高,是个值得好好学习的东西。
用排序功能来举例,排序是经常使用到的,比如冒泡排序:
Sub BubbleSort(l())
Dim i As Long, j As Long
For i = 1 To UBound(l)
For j = i + 1 To UBound(l)
If l(i) > l(j) Then
Call Swap(l, i, j)
End If
Next j
Next i
End Sub
Function Swap(l(), Low As Long, High As Long)
Dim iTemp
iTemp = l(Low)
l(Low) = l(High)
l(High) = iTemp
End Function
有了这个函数,只要传入1个一维数组,函数执行完后数组就有序了。 但是,如果需要排序的是个二维数组的话,就不得不把排序函数重新写过一次,如果是结构体,又得重新写过…… 接口的使用,就可以最小化的来修改这些东西。 对于这个排序函数,不管传入的是什么数据,排序算法是固定的,不同的地方是:
排序算法是固定的,要修改的是这2个功能,只要传入的东西里面具有这2个功能就可以了,具有功能的东西,也就是类,类能有自己的方法。 但是又不能传入某种具体的类,因为数据的不同,这2个方法也是不相同的,这就需要接口了。接口ISort定义2个功能:
Function Swap(i As Long, j As Long)
End Function
Function Less(i As Long, j As Long) As Boolean
End Function
然后排序函数传入的是这个接口:
Sub BubbleSort(I_Sort As ISort, Low As Long, High As Long)
Dim i As Long, j As Long
For i = Low To High
For j = i + 1 To High
If I_Sort.Less(j, i) Then
I_Sort.Swap i, j
End If
Next j
Next i
End Sub
一维数据的实现:
Implements ISort
Private arr() As Variant
Property Let Data(Value As Variant)
arr = Value
End Property
Property Get Data() As Variant
Data = arr
End Property
'比较
Private Function ISort_Less(i As Long, j As Long) As Boolean
ISort_Less = arr(i) < arr(j)
End Function
'交换
Private Function ISort_Swap(i As Long, j As Long) As Variant
Dim tmp As Variant
tmp = arr(i)
arr(i) = arr(j)
arr(j) = tmp
End Function
二维数组实现接口:
Implements ISort
Private Type LowHigh
Low As Long
High As Long
End Type
Private arr() As Variant
Private i_col As Long '要排序的列
Private Col_Bound As LowHigh '列的上下标
Property Let SortCol(iCol As Long)
i_col = iCol
End Property
Property Let Data(Value As Variant)
arr = Value
Col_Bound.Low = LBound(arr, 2)
Col_Bound.High = UBound(arr, 2)
End Property
Property Get Data() As Variant
Data = arr
End Property
'比较
Private Function ISort_Less(i As Long, j As Long) As Boolean
ISort_Less = arr(i, i_col) < arr(j, i_col)
End Function
'交换
Private Function ISort_Swap(i As Long, j As Long) As Variant
Dim tmp As Variant
Dim k As Long
For k = Col_Bound.Low To Col_Bound.High
tmp = arr(i, k)
arr(i, k) = arr(j, k)
arr(j, k) = tmp
Next k
End Function