带有私有variables的VBA工厂方法

所以我有一个Factory类与方法Create_product

Product碰巧有我想由Factory设置的私有variables,但是如果他们是私有的,我怎么能让Factory访问他们?

最好我希望在创buildProduct新实例后不可能改变它们。

朋友

修改表单模块或类模块中过程的定义,使过程可以从类之外的模块中调用,但是在类中定义的部分工程中。 朋友程序不能在标准模块中使用。

句法

 [Private | Friend | Public] [Static] [Sub | Function | Property] procedurename 

所需的过程名称是在整个项目中可见的过程的名称,但对于该类别的控制器不可见。

备注

公共程序可以在任何地方被调用,甚至是类的实例的控制器。 声明一个过程Private可以防止对象的控制器调用该过程,但是也可以防止该过程在定义类本身的项目中被调用。 朋友在整个项目中使该过程可见,而不是对象实例的控制器。 朋友只能在表单模块和类模块中出现,只能修改过程名称,而不能修改variables或types。 课程中的程序可以访问项目中所有其他课程的朋友程序。 朋友程序不会出现在他们class级的types库中。 朋友程序不能迟到。

像1一样使用单例类

创build名为Singleton的表单模块:

 Private SingleInsts As Collection Private instCount As Double Public isCalled As Boolean Private Sub UserForm_Initialize() Me.Hide Me.isCalled = False End Sub Private Function setInstance(name As String) As Object Dim Obj As Object If SingleInsts Is Nothing Then Set SingleInsts = New Collection instCount = SingleInsts.Count ReDim singleNames(instCount + 1) Me.isCalled = True Select Case name Case "Example" Set Obj = New Example Case "Other" Set Obj = New Other 'etc. etc - Case ... for all classes Case Else Err.Raise vbObjectError + 800, Err.Source & "|" & Me.name & "." & "setInstance", name & " is not a classname" End Select Me.isCalled = False SingleInsts.Add Obj, name Set setInstance = Obj Exit Function End Function Public Function getInstance(name As String) As Object On Error Resume Next If (SingleInsts(name) Is Nothing) And False Then 'this way only by error - when SingleInsts(name) doesn't exist Set getInstance = setInstance(name) Else Set getInstance = SingleInsts(name) End If End Function Public Function errNew(errstr As String) Err.Raise vbObjectError + 703, errstr End Function 

这个函数必须在所有类中:

 Private Sub Class_Initialize() If Not Singleton.isCalled Then Singleton.errNew TypeName(Me) End Sub 

然后调用“factory”方法来获取对象(一个对象只能被实例化一次 – 请参阅Singleton中的getInstance方法)

 Sub fo() set alfa = Singleton.getInstance("Example") End sub