scholzr
scholzr

Reputation: 245

choose active namespace dynamically

First off, I am not sure that the way that I am planning (and will describe below) is necessarily the "best" way to do this, so I am open to suggestions. I have an application that I need to add the ability to collect information from hardware monitors during runtime. I need to build this communication framework in an extensible way so that I can support multiple different monitors with different communications protocols.

My plan was to write a class for each different monitor, each of which will implement the same methods. It would look something like below:

Monitor1.vb:

Public Function GetHR() as integer
    //Code specific to interact with Monitor 1
    return HR as integer
End Function

Monitor2.vb:

Public Function GetHR() as integer
    //Code specific to interact with Monitor 2
    return HR as integer
End Function

I would then on the implementation page select the active monitor and call the function Implementation.vb:

ActiveMon = Monitor1
CurrentHR = ActiveMon.GetHR()

If this is an acceptable method for setting the active class, how would I go about setting it (I'm guessing that my example above of simply setting a variable is not the correct way to do so). If this is not the best method, how should I do this?

Upvotes: 1

Views: 85

Answers (1)

beezir
beezir

Reputation: 460

Generally for this type of thing, you either want to use interfaces or inheritance. If the classes have some common shared code, inheritance would be the better option. If it just needs to present common methods, an interface will work just fine:

Interface IMonitor
    Function GetHR() as Integer
End Interface

Public Class Monitor1
    Implements IMonitor

    Public Function GetHR() as Integer Implements IMonitor.GetHR
        ' Do Stuff
        Return someValue
    End Function
End Class

Public Class Monitor2
    Implements IMonitor

    Public Function GetHR() as Integer Implements IMonitor.GetHR
        ' Do other Stuff
        Return someValue
    End Function
End Class

Then you can have a variable of the interface type and assign to it:

Dim myMonitor as IMonitor
myMonitor = new Monitor1()
Dim result = myMonitor.GetHR() ' Some result
myMonitor = new Monitor2()
result = myMonitor.GetHR()     ' Some other result

Upvotes: 2

Related Questions