Share via


介面架構多型

更新:2007 年 11 月

介面是另外一種讓您在 Visual Basic 中進行多型 (Polymorphism) 的方法。與類別一樣,介面也會描述屬性和方法,但不同的是介面無法提供任何實作 (Implementation)。多重介面的優點在於,允許軟體元件的系統逐步發展而不需要破壞現有的程式碼。

若要達到介面的多型,您可以在多個類別中以不同的方法實作介面。用戶端應用程式可以完全相同的方法來使用舊的或新的實作。介面架構多型的優點是您不需要重新編譯現有的用戶端應用程式,就可讓它們與新的介面實作一起使用。

下列範例定義名為 Shape2 的介面,這是用名為 RightTriangleClass2 及 RectangleClass2 的類別所實作而成。名為 ProcessShape2 的程序呼叫 RightTriangleClass2 或 RectangleClass2 執行個體的 CalculateArea 方法:

Sub TestInterface()
    Dim RectangleObject2 As New RectangleClass2
    Dim RightTriangleObject2 As New RightTriangleClass2
    ProcessShape2(RightTriangleObject2, 3, 14)
    ProcessShape2(RectangleObject2, 3, 5)
End Sub

Sub ProcessShape2(ByVal Shape2 As Shape2, ByVal X As Double, _
      ByVal Y As Double)
    MsgBox("The area of the object is " _
       & Shape2.CalculateArea(X, Y))
End Sub

Public Interface Shape2
    Function CalculateArea(ByVal X As Double, ByVal Y As Double) As Double
End Interface

Public Class RightTriangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a right triangle. 
        Return 0.5 * (X * Y)
    End Function
End Class

Public Class RectangleClass2
    Implements Shape2
    Function CalculateArea(ByVal X As Double, _
          ByVal Y As Double) As Double Implements Shape2.CalculateArea
        ' Calculate the area of a rectangle. 
        Return X * Y
    End Function
End Class

請參閱

工作

HOW TO:建立和實作介面

概念

繼承架構多型