首先,添加一個標准模塊:
''''單一類模式,需定義全局變量作為唯一的實例
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() ,得到全局唯一的實例