Instead of getting complicated with it, and using a roundabout approach, just use the tools meant for the job:
Class Module IFoo
Public Sub Bar()
' Interface methods are empty
End Sub
Class Module Foo
Private Type TFoo
Baz As String
End Type
Private this As TFoo
Implements IFoo
Private Sub Class_Initialize()
this.Baz = "I am a class that implements IFoo."
End Sub
Private Sub IFoo_Bar()
' Do Something
Debug.Print this.Baz
End Sub
Module Baz
Sub RunBaz()
Dim MyFoo As IFoo
' Note that this WILL NOT work. Nothing happens.
Set MyFoo = New IFoo
Debug.Print MyFoo.Bar
' Set MyFoo to be equal to a Foo (which implements IFoo)
Set MyFoo = New Foo
Debug.Print MyFoo.Baz
End Sub
This makes the methods only visible when the methods are being accessed through an interface which makes them public. Therefore, in order to use the methods in Foo
we must first create an instance of Foo
using an IFoo
variable type.
Then, it is as simple as creating a new class which creates a Foo
from an IFoo
for its own use.
Class Module IImportantWorker
Public Sub DoSomethingImportant()
End Sub
Class Module ImportantWorker
Private Type TImportantWorker
Implementation As IFoo
End Type
Private this As TImportantWorker
Implements IImportantWorker
Private Sub Class_Initialize()
Set this.Implementation = New Foo
End Sub
Public Sub IImportantWorker_DoSomethingImportant()
this.Implementation.Bar
End Sub
You could get fancy from here and make a property of Foo that is exposed by IFoo
that tells it whether or not it can work. This would have to be exposed through the IFoo interface (or, alternatively a separate interface so that the two interfaces must be used in conjunction).
Without locking the class (which I wouldnt recommend anyways, it seems foolish and pointless) Foo
will still allow Bar
if it is created as a IFoo
. But if you just make Foo = New Foo
then Foo
will do nothing (or rather, expose nothing).
For additional resources, I highly recommend reading these excellent posts that go into greater depth about the processes:
Is VBA an OOP language, and does it support polymorphism?
https://rubberduckvba.wordpress.com/2016/06/16/oop-vba-pt-1-debunking-stuff/
https://rubberduckvba.wordpress.com/2016/07/05/oop-vba-pt-2-factories-and-cheap-hotels/