0

我正在尝试在我的项目中更多地使用接口。我在网上看到的很多例子都很琐碎(但很有帮助)。请看下面的代码:

Public Class Animal
    Implements Eatable
    Public Overridable Sub Eat() Implements Eatable.Eat
        MsgBox("Animal Eat no arguement")
    End Sub
Public Overridable Overloads Sub Eat(ByVal food As String) Implements Eatable.Eat
    MsgBox("Animal Eat food arguement")
End Sub
End Class

Public Class Horse
    Inherits Animal
    Implements Eatable
    Public Overrides Sub Eat()
        MsgBox("Horse Eat no arguement")
    End Sub
    Public Overloads Sub Eat(ByVal food As String)
        MsgBox("Horse Eat food arguement")
    End Sub
End Class

Public Interface Eatable
    Sub Eat()
    Sub Eat(ByVal localEat As String)
End Interface

Public Class Form1

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        TestFunction(1)
    End Sub

    Public Sub TestFunction(ByVal intTest As Integer)
        Dim e1 As Eatable
        If intTest = 1 Then
            e1 = New Horse
        Else
            e1 = New Animal
        End If
        'Functionality specific to e1 from here
    End Sub
End Class

我在某处读到,以我在 TestFunction 中所做的方式使用多态性是不好的做法,即根据 intTest 的值将 e1 实例化为马或动物。如果是这种情况,那么有人可以推荐一种设计模式吗?

4

1 回答 1

0

这段代码基本上没有任何问题(除了你的界面应该以大写“I”开头):

Dim e1 As Eatable
If intTest = 1 Then
  e1 = New Horse
Else
  e1 = New Animal
End If

只要您的期望是只需要处理一个 IEatable 对象。

如果您最终需要确定您拥有“哪种”动物,如下所示:

If TypeOf e1 Is Horse Then
  MessageBox.Show("Yeah, you're a horse")
Else
  MessageBox.Show("You are not a horse")
End If

那么你最终设计了错误的东西。

于 2012-07-26T17:35:24.207 回答