简单的界面 - 可飞行
接口 Flyable 是一个类模块,代码如下:
Public Sub Fly()
' No code.
End Sub
Public Function GetAltitude() As Long
' No code.
End Function
类模块 Airplane 使用 Implements 关键字告诉编译器引发错误,除非它有两个方法:Flyable_Fly() sub 和 Flyable_GetAltitude() 函数返回 Long。
Implements Flyable
Public Sub Flyable_Fly()
Debug.Print "Flying With Jet Engines!"
End Sub
Public Function Flyable_GetAltitude() As Long
Flyable_GetAltitude = 10000
End Function
第二类模块 Duck 也实现了 Flyable:
Implements Flyable
Public Sub Flyable_Fly()
Debug.Print "Flying With Wings!"
End Sub
Public Function Flyable_GetAltitude() As Long
Flyable_GetAltitude = 30
End Function
我们可以写一个接受任何 Flyable 值的例程,知道它会响应 Fly 或 GetAltitude 的命令:
Public Sub FlyAndCheckAltitude(F As Flyable)
F.Fly
Debug.Print F.GetAltitude
End Sub
由于界面已定义,因此智能感知弹出窗口将显示 Fly 的 Fly 和 GetAltitude。
当我们运行以下代码时:
Dim MyDuck As New Duck
Dim MyAirplane As New Airplane
FlyAndCheckAltitude MyDuck
FlyAndCheckAltitude MyAirplane
输出是:
Flying With Wings!
30
Flying With Jet Engines!
10000
请注意,即使子程序在 Airplane 和 Duck 中都被命名为 Flyable_Fly,当变量或参数定义为 Flyable 时,它也可以称为 Fly。如果变量专门定义为 Duck,则必须将其称为 Flyable_Fly。