用于在2个com对象之间切换的最佳vb.net设计模式

时间:2012-08-06 18:18:45

标签: .net vb.net design-patterns

挑战是提出最好的vb.net设计模式,允许在两个不同的大型机之间切换访问com对象。所有这一切当然不需要改变业务逻辑。

到目前为止,我提出的是一种工厂类型的方法(参见下面的压缩伪代码)。我有2个类,它们基于具有相同方法和属性但具有不同底层对象特定方法的枚举开关进行实例化。

我是在正确的轨道上还是应该采取另一种方法?谢谢你的帮助。

Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Private MFA as MFSession = New MFSession(Enums.mfaccesstype.type1)
Private Sub Form1_Load()
    MFA.GotoScreen("XYZ")
End Sub
End Class

Public Class MFSession
Private SystemAccess As Object
End Property
Sub New(ByVal AccessType As Enums.mfaccesstype)
    Select Case AccessType
        Case Enums.mfaccesstype.type1
            SystemAccess = New AccessType1()
        Case Enums.mfaccesstype.type2
            SystemAccess = New AccessType2()
    End Select
End Sub

Public Sub GotoScreen(ByVal ScreenName As String, Optional ByVal Window As String = "")
    SystemAccess.GoToScreen(ScreenName)
End Sub
End Class

Public Class AccessType1
Private Type1Object As Object = CreateObject("comobj.Type1Object")

Sub New()
    'new session housekeeping
End Sub

Public Sub GotoScreen(ByVal ScreenName As String)
    'specialize Type1 method for going to 'ScreenName' here
End Sub

End Class


Public Class AccessType2
Private Type2Object As Object = CreateObject("comobj.Type2Object")

Sub New()
    'new session housekeeping
End Sub

Public Sub GotoScreen(ByVal ScreenName As String)
    'specialized Type2 method for going to 'ScreenName' here
End Sub
End Class

1 个答案:

答案 0 :(得分:1)

你很亲密。

首先定义公共接口:

Public Interface ISession 'could be abstract class instead if there is common code you'd like to share between the subclasses

   Sub GotoScreen(ByVal ScreenName As String) 

End Interface

其次,定义子类:

Public Class Type1Session Implements ISession

   Private innerComObj As SomeComObject

   Public Sub GotoScreen(ByVal ScreenName As String)
      'type1-specific code using innerComObj
   End Sub 

End Class

Public Class Type2Session Implements ISession

   Private anotherComObj As SomeOtherComObject

   Public Sub GotoScreen(ByVal ScreenName As String)
      'type2-specific code using anotherComObj
   End Sub 

End Class

然后,您可以创建一个工厂,该工厂将接受枚举或其他arg并返回具体的Type1Session或Type1Session。

这可以在专门的课程中完成:

Public Class SessionFactory

   Public CreateSession(criteria) As ISession 
      'select case against your enum or whatever to create and return the specific type
   End Sub

End Class

如果你去抽象(VB中的MustOverride)类而不是接口,那么将工厂方法放在超类中也是预先设定的。

最后,COM完全是关于接口的,所以如果你控制了COM组件源,你可以让它们直接实现公共接口。