0

Please have a look at the following question: Favor composition over inheritance

The accepted answerer says: " it extends Hashtable, in order to reuse its methods and to avoid reimplementing some of them using delegation". I am not sure what the answerer means by: reimplementing some of them using delegation. What does the answerer mean?

I am familiar with Delegates and the Observer design pattern.

Community
  • 1
  • 1
w0051977
  • 15,099
  • 32
  • 152
  • 329

1 Answers1

5

When using composition, if you want to support a method that the underlying class has, you must define your own implementation that simply delegates (or uses) the same method on the underlying class. It can be tempting to use inheritance in this case to avoid writing that simple (delegated) method, but inheritance really should be used only when an IS-A relationship exists.

For example,

 public class Foo
 {
     public virtual void Bar()
     {
         // do something
     }
 }

 public class InheritedFromFoo : Foo
 {
      // we get Bar() for free!!!
 }

 public class ComposedWithFoo
 {
      private Foo _foo;

      public void Bar()
      {
          _foo.Bar();  // delegated to the Foo instance
      }
 }
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Thanks. I understand inheritance. The question was about composition. Are you able to modify the example with an example of composition that uses delegates or point me towards a webpage? – w0051977 Jan 20 '13 at 18:09
  • @w0051977 no, the question wasn't about delegates, it was about how to reuse behavior via either inheritance or composition. Composition, by definition, uses delegation - the behavior of the class reuses the underlying classes to provide its own behavior, i.e., it delegates some portion of it's behavior to the class it is using via composition. – tvanfosson Jan 20 '13 at 18:14
  • Thanks for clarifying that +1. I now understand that "delegation" has nothing to do with delegates. Is there an example that shows this delegation? – w0051977 Jan 20 '13 at 18:16
  • 1
    @w0051977 - the ComposedWithFoo class in the example shows the Bar() method being delegated to the Bar() method on the underlying Foo instance. – tvanfosson Jan 20 '13 at 18:18