Reputation: 5543
I am creating a project in VBA to automate handling of asynchronous quasi-multithreading (mouthful, sorry). This revolves around creating and running multiple copies of a class which Implements
a certain interface, and raises some known events when the async task is complete. The interfacing is similar to this example
My program calls the class to execute its code, and listens to the events raised, that's all working fine. Now my final task is to take any given class which Implements
the appropriate interface, and make multiple copies to set running in parallel.
How do I make copies of a class which is passed to a routine?
How can I take a class reference and make several New
versions?
Or in code, each one of my thread classes (the classes which handle the async class which is passed) will have a Worker
property to save their task.
Private workerObject As IWorker
Public Property Set Worker(workObj As IWorker) 'pass unknown class with IWorker interface
'What goes here?
Set workerObject = workObj
'This won't work as then every thread points to the same worker
'I want something to create a New one, like
Set workerObject = New ClassOf(workObj)
'But of course that doesn't work
End Property
Upvotes: 2
Views: 72
Reputation: 175916
You would need to inspect the possible types and act accordingly:
Dim workerObject As IWorker
If TypeOf workObj Is ImplementingClass1 Then
Set workerObject = New ImplementingClass1
ElseIf TypeOf workObj Is ImplementingClass2 Then
Set workerObject = New ImplementingClass2
End If
Alternatively you could add a factory method to the interface:
Public Function CreateNew() As IWorker: End Function
Implement it in the classes:
Public Function IWorker_CreateNew() As IWorker
Set IWorker_CreateNew = New ImplementingClass1
End Function
And then:
Set workerObject = workObj.IWorker_CreateNew()
Upvotes: 2