首先,添加一个标准模块:
''单一类模式,需定义全局变量作为唯一的实例
Public glbPlcObj As clsPlc
Public intPlcCounter As Integer
再添加一个类模块:
Private blnLegalInstance As Boolean ''只有一个合法的实例可以打开串口的端口
Private strCommPort As Variant
Private strSettings As String
Public Property Get CommPort() As Variant
CommPort = strCommPort
End Property
Public Property Let CommPort(ByVal vNewValue As Variant)
strCommPort = vNewValue
End Property
Public Property Get Settings() As String
Settings = strSettings
End Property
Public Property Let Settings(ByVal vNewValue As String)
strSettings = vNewValue
End Property
Private Sub Class_Initialize()
If intPlcCounter = 0 Then
blnLegalInstance = True
Set glbPlcObj = Me ''产生唯一的实例
intPlcCounter = intPlcCounter + 1
Else
blnLegalInstance = False
End If
End Sub
Public Function GetPlcSingletonObj() As clsPlc ''得到唯一的实例
Set GetPlcSingletonObj = glbPlcObj
End Function
Public Function ComPortOpened() As Boolean ''开始通讯,不是唯一的实例无法加载PLC窗体
If blnLegalInstance = True Then
Load frmPlcCom
''端口正常打开时为true,否则请重新设置端口
ComPortOpened = frmPlcCom.MscommPortOpen()
End If
End Function
Private Sub Class_Terminate()
If blnLegalInstance = True Then
Set glbPlcObj = Nothing
intPlcCounter = 0
End If
End Sub
如何调用:
先创建一个新实例,然后调用GetPlcSingletonObj() ,得到全局唯一的实例