2

我正在为运行 Windows XP 的设备编写应用程序。该设备有 2 个版本,每个版本都有自己的 API 来与设备的软件进行通信。我正在编写的应用程序需要从 API 中提取相同的数据。我的问题是如何编写一个应用程序,该应用程序将在运行时检测它所在的设备版本并使用适当的 API。我已经弄清楚如何读取注册表以确定设备。

我创建了一个接口,其中包含所有常用方法以及实现该接口的每个设备的类。现在我需要知道如何在运行时激活正确的。

 Public Interface IAPI

    Sub InitializeMachine()

    Function GetActiveProgram() As String

    Function GetActiveGCodes() As String

    Function GetCurrentBlockNumber() As Integer

    ''#etc...

End Interface

''#Mill API
Public Class CMAPI : Implements IAPI

    Private ObjMachine As Okuma.CMDATAPI.DataAPI.CMachine
    Private ObjPgm As Okuma.CMDATAPI.DataAPI.CProgram

    Public Sub New()

    End Sub

    Public Function GetActiveGCodes() As String Implements IAPI.GetActiveGCodes
        Try
            Return ObjPgm.GetGCodes
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetActiveProgram() As String Implements IAPI.GetActiveProgram
        Try

            Return ObjPgm.GetActiveProgramName

        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetCurrentBlockNumber() As Integer Implements IAPI.GetCurrentBlockNumber
        Try

            Return ObjPgm.GetCurrentBlockNumber

        Catch ex As Exception
            Throw ex
        End Try
    End Function

    ''#....
End Class

''#Lathe API
Public Class CLAPI : Implements IAPI
    Private ObjMachine As Okuma.CLDATAPI.DataAPI.CMachine
    Private ObjPgm As Okuma.CLDATAPI.DataAPI.CProgram

    Public Sub New()

    End Sub

    Public Function GetActiveGCodes() As String Implements IAPI.GetActiveGCodes
        Try
            Return ObjPgm.GetGCodes
        Catch ex As Exception
            Throw ex
        End Try
    End Function

    Public Function GetActiveProgram() As String Implements IAPI.GetActiveProgram
        Try

            Return ObjPgm.GetActiveProgramName

        Catch ex As Exception
            Throw ex
        End Try
    End Function

''#...
End Class
4

2 回答 2

2

未经测试,理论是正确的 - 可能有错别字:P

Dim rightAPI As IAPI

If CheckForTypeCMAPI() = true Then ' You said you can determine which device youre on, replace this with the right function
    rightAPI = new CMAPI()
Else
    rightAPI = new CLAPI()
End If

' Use rightAPI wherever you need it
MessageBox.Show(rightAPI.GetActiveProgram())
于 2010-02-15T16:52:42.337 回答
1

我会使用工厂方法:

Dim rightAPI As IAPI


rightAPI = APIFactory.GetAPI(HowYouDistinguishDevice)

' Use rightAPI wherever you need it
MessageBox.Show(rightAPI.GetActiveProgram())


public class APIFactory

    public shared function GetAPI(string HowYouDistinguishDevice) as IAPI
        dim oAPI as IAPI
        'do whatever it is you need to do to determine which api to use
        if CMAPI then oAPI = new CMAPI
        if CLAPI then oAPI = new CLAPI
        'or you could use select, whatever
        return oAPI
    end function
end class
于 2010-02-15T18:20:24.890 回答