Jump to content

Example for Delegation pattern


Recommended Posts

Personally I don't think of delegation as a pattern, just a natural consequence of encapsulation. 

In your example, you've included demonstrating polymorphism and delegation. If you want to focus only on delegation, I would probably make some adjustments:

  1. Two classes - "Duck" and "QuakingFunction".
  2. Duck class contains a QuakingFunction object. It has a 'constructor' or method to set the required object for that task (dependency injection).
  3. Duck class exposes the static "Quak" method. This method internally calls QuakingFunction.Quak() method of the object (your delegation).

Note - if you make the QuakingFunction.Quak() method virtual, it lets you implement new child classes in the future that Quak differently (Strategy pattern). You inject the one you want at the time.

You don't need the derived Duck classes at all in order to demonstrate delegation. The Duck.Quak() method can of course be called with the child class objects so that they too can quack .. like a duck (Inheritance).

Link to comment

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.