Home Create copy of class passed as argument
Reply: 1

Create copy of class passed as argument

Greedo
1#
Greedo Published in 2017-12-07 15:02:22Z

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
Alex K.
2#
Alex K. Reply to 2017-12-07 15:39:04Z

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()
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317077 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO