I am interested in hearing your opinion on the approach I have taken to have inherited classes initialize their base class.
Here's a Machines collection class from that maintains a list of Machine objects. Each Machine needs to be able to inform its parent, using a delegate, of something they do but they do not have a reference to the parent:
Public Delegate Sub MachineDelegate(ByRef item As Machine) Public MustInherit Class Machines Private _items As New List(Of Machine) Public Function Create() As Machine Dim item As Machine = CreateItem() _items.Add(item) PostCreationHandler(item) Return item End Function ' Create derived object Public MustOverride Function CreateItem() As Machine Public Sub ChildMachineDidSomething(ByRef item As Machine) ' Handle child object event Debug.Print("Machine did something") End Sub ' Called once object has been created Protected Overridable Sub PostCreationHandler(ByRef item As Machine) item.MachineDelegate = AddressOf ChildMachineDidSomething End Sub End Class Public Class Machine Public MachineDelegate As MachineDelegate Public Sub DoMachineThing() If Not MachineDelegate Is Nothing Then MachineDelegate(Me) End Sub End Class
The child objects will use a
MachineDelegate to inform their parent, passing themselves as a reference.
Inherited Cars and Car classes would look like this and have their own delegate to handle Car-related notifications:
Public Delegate Sub CarDelegate(ByRef item As Car) Public Class Cars Inherits Machines ' Create derived object Public Overrides Function CreateItem() As Machine Dim item As Car = New Car CreateItem = item End Function Public Sub ChildCarDidSomething(ByRef item As Car) ' Handle child object event Debug.Print("Car did something") End Sub ' Called once object has been created Protected Overrides Sub PostCreationHandler(ByRef item As Machine) Dim car As Car = item MyBase.PostCreationHandler(item) car.CarDelegate = AddressOf ChildCarDidSomething End Sub End Class Public Class Car Inherits Machine Public CarDelegate As CarDelegate Public Sub DoCarThing() If Not CarDelegate Is Nothing Then CarDelegate(Me) End Sub End Class
I create an overridable
PostCreationHandler where object-specific initialization is to be handled once an object is created and I am using
MyBase.PostCreationHandler to make sure the object gets properly initialized at every level in the inheritance chain.
My goal is to avoid giving child objects a reference to their parent.
My question is is this OK and is there a better approach to doing this?