Delegates: Difference between revisions
Content added Content deleted
(New page: {{task}} A delegate is a helper object used by another object. The delegator may delegate some operations to the delegate, and provide a default implementation when there is not delegate ...) |
No edit summary |
||
Line 13: | Line 13: | ||
Delegate: |
Delegate: |
||
* Implement "thing". |
* Implement "thing". |
||
* May implement "other", but don't implement it for this example. |
|||
==[[Python]]== |
==[[Python]]== |
Revision as of 20:01, 3 October 2007
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
A delegate is a helper object used by another object. The delegator may delegate some operations to the delegate, and provide a default implementation when there is not delegate or the delegate does not implement the operation. This pattern is heavily used in Cocoa framework on Mac OS X
Objects responsibilities:
Delegator:
- Keep an optional delegate instance.
- Allow setting the delegate when creating the instance or later.
- Delegate the methods "thing" and "other" to the delegate.
- Provide default implementation if there is no delegate or the delegate does not implement one of the method.
Delegate:
- Implement "thing".
- May implement "other", but don't implement it for this example.
Python
class Delegator: def __init__(self, delegate=None): self.delegate = delegate def thing(self): if hasattr(self.delegate, 'thing'): return self.delegate.thing() return 42 def other(self): if hasattr(self.delegate, 'other'): return self.delegate.thing() return 5 class Delegate: def thing(self): return 37 if __name__ == '__main__': # No delegate a = Delegator() assert a.thing() == 42 assert a.other() == 5 # With delegate a.delegate = Delegate() assert a.thing() == 37 assert a.other() == 5