接口的.net设计模式

时间:2012-07-26 16:50:33

标签: vb.net design-patterns

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

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实例化为马或动物。如果是这种情况,那么有人可以推荐一种设计模式吗?

1 个答案:

答案 0 :(得分: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

然后你最终设计错了。