一类中的多个接口 - 可飞行和可扩展
使用 Flyable
示例作为起点,我们可以使用以下代码添加第二个接口 Swimmable
:
Sub Swim()
' No code
End Sub
Duck
对象可以飞行和游泳:
Implements Flyable
Implements Swimmable
Public Sub Flyable_Fly()
Debug.Print "Flying With Wings!"
End Sub
Public Function Flyable_GetAltitude() As Long
Flyable_GetAltitude = 30
End Function
Public Sub Swimmable_Swim()
Debug.Print "Floating on the water"
End Sub
Fish
类也可以实现 Swimmable
:
Implements Swimmable
Public Sub Swimmable_Swim()
Debug.Print "Swimming under the water"
End Sub
现在,我们可以看到 Duck
对象一方面可以作为 Flyable
传递给 Sub,另一方面可以传递给 Swimmable
:
Sub InterfaceTest()
Dim MyDuck As New Duck
Dim MyAirplane As New Airplane
Dim MyFish As New Fish
Debug.Print "Fly Check..."
FlyAndCheckAltitude MyDuck
FlyAndCheckAltitude MyAirplane
Debug.Print "Swim Check..."
TrySwimming MyDuck
TrySwimming MyFish
End Sub
Public Sub FlyAndCheckAltitude(F As Flyable)
F.Fly
Debug.Print F.GetAltitude
End Sub
Public Sub TrySwimming(S As Swimmable)
S.Swim
End Sub
此代码的输出是:
飞检…
飞翔的翅膀!
三十
乘坐喷气式飞机飞行!
10000
游泳检查……
漂浮在水面上
在水下游泳