说我有2个加载项 A 和 B - 都使用来自共享加载项 C 的VB函数(即 A 和 B 引用VB项目 C 。
C 会在检测到错误时将某些消息记录到文件(例如C.Log
)。当从调用函数时,我希望将 C 日志记录到A.log
,当从 B 调用函数时,我想要B.log
。
使用日志文件名在 C 中设置全局变量的天真方法将不起作用,因为该变量是Singleton,因此最后一个设置变量的项目( A ,或 B )将获胜。
如何在VBA中轻松完成?
答案 0 :(得分:0)
好的 - 所以这是我提出的解决方案(相当一些代码,但似乎工作正常):
我有一个日志记录项目,其日志记录界面ILog
(Instancing PublicNotCreatable
)就像
这样:
Public Sub Error(sLogMessage As String)
end sub
Public Sub Warning(sLogMessage As String)
end sub
' etc.
当然还有一个实现类CLog
,它只是将消息写入日志文件
和一个公共函数,以便调用者可以获得记录器的新实例:
Public Function New_Log(ByVal logFilePathAndName) As ILog
Set New_CLog = New CLog
New_CLog.Initialise logFilePathAndName
End Function
然后项目C 必须在其初始化中获得ILog
实例的类/类中包含所有代码。例如CSharedClass
可能如此:
Private Log as ILog ' note: the var is intentionally NOT called moLog
Public Sub Initialise(oLogger as ILog)
Set Log = oLogger
End Sub
' other functions in this class that want to log just use this:
Public Sub SomeProcedure()
Log.Error("error text")
End Sub
此项目还必须有一个公共函数让调用者创建一个实例,如下所示:
Public Sub New_SharedClass(oLogger as ILog) as CSharedClass ' NOTE: you may want to use an interface instead
Set New_SharedClass = New CSharedClass
New_SharedClass.Initialise oLogger
End Sub
然后项目A和B 可以使用这样的日志记录:
Private moLog as ILog
Public Function Log() as ILog
' log-file name is of course different for Proejct B
If moLog is Nothing then Set moLog = New_Log("ProjectA.log")
Set Log = moLog
End Function
项目A / B中的所有其他程序现在可以像这样编写日志消息(与共享项目中的相同)
Log.Error("Error text")
当项目A / B想要使用共享项目时,它可以这样做
Private moSharedClass as CSharedClass
Public Function SharedClass() as CSharedClass
If moSharedClass is Nothing then Set moSharedClass = New_SharedClass(Log)
Set SharedClass = moSharedClass
End Function
现在项目A / B中想要在共享类上调用proc的任何代码都可以这样做:
SharedClass.SomeProcedure()
并且SomeProcedure
中写入的日志消息将以正确的日志文件
注意:我决定打破一些自己的命名规则,以便所有项目都可以使用相同的代码进行日志记录(这样做的好处是我可以将程序从项目A / B移动到共享项目,反之亦然)