Aggregation

  • Thread starter Thread starter Nice Chap
  • Start date Start date
N

Nice Chap

Aggregation in COM was defined as 'Exposing an interface of an inner object
by the outer object as though it were an interface of the outer object'. Is
this type of aggregation possible in vb.net( or c#).
 
Aggregation in COM worked by having all IUnknown calls go through the outter
object, and all QueryInterface calls on the outter object would include
calls to the inner object. In many ways, this was used to simulate the
object reuse effects of inheritance. In .NET, you can create a base class
object, then inherit that object in a derrived object. The derrived object
will automatically include the interfaces and implemenation of the base
class in addition to its own. However, there are nuances in inheritance that
aren't covered by aggregation and vice-versa. One thing to note is that in
..NET there is no multiple-inheritance. To get around this, you have to
delegate. In other words, you implement the interface of a contained object
in the container object, and manually delegate the calls to an inner object.

-Rob Teixeira [MVP]
 
Rob,
I have been wondering how to handle a pattern as such:

Public Class Main

Public Class A
End Class

Public Class B
End Class

End Class

This seems to be a way around the single multiple inheritance limit. I
wonder if this is a good idea and, if it is, how would one implement
delegation in this example? If not, could you give some simple code on how
to delegate to handle the single multiple inheritance limit?
TIA,
Steve
 
Well, for starters, the classes don't have to be nested - classes A and B
can be defined outside Main if you like.
Next, Class Main can inherit from one of them - for this example, let's say
it's A. That takes care of one issue.
Before proceeding, you'll need to create an Interface for class B (let's
call it IClassB). This interface lists all the public members of B.
Now, you can implement IClassB in your class Main. For the implementation,
you'll need to create a private instance of B, and call that instance's
members from your implementation of IClassB in Main.

Public Interface IClassB
Sub DoSomething ( )
End Interface

Public Class B
Implements IClassB

Public Sub DoStuff ( ) Implements IClassB.DoStuff
' base implementation code goes here
End Sub
End Interface

Public Class Main
Inherits A
Implements IClassB

Private privateB As New B

Public Sub DoStuff( ) Implements IClassB.DoStuff
privateB.DoStuff( ) ' <--- delegation to class B instance here
End Sub
End Class

Again, there are nuances that prevent this from being a "true" substitution
of inheritance. For instance, Main has no way of dealing with B's Protected
members in this sample (unless you use Reflection and have enough access
permissions to invoke non-public members). But this should serve as a simple
example of the technique.

-Rob Teixeira [MVP]
 
Back
Top