Anonymous user
Delegates: Difference between revisions
added ruby
No edit summary |
(added ruby) |
||
Line 381:
self.delegate = None
def operation(self):
if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
return self.delegate.thing()
return 'default implementation'
Line 402:
a.delegate = Delegate()
assert a.operation() == 'delegate implementation'</lang>
=={{header|Ruby}}==
<lang ruby>class Delegator
def initialize
@delegate = nil
end
def delegate
@delegate
end
def delegate=(x)
@delegate = x
end
def operation
if @delegate.respond_to?(:thing)
@delegate.thing
else
'default implementation'
end
end
end
class Delegate
def thing
'delegate implementation'
end
end
if __FILE__ == $PROGRAM_NAME
# No delegate
a = Delegator.new
puts a.operation # prints "default implementation"
# With a delegate that does not implement "thing"
a.delegate = 'A delegate may be any object'
puts a.operation # prints "default implementation"
# With delegate that implements "thing"
a.delegate = Delegate.new
puts a.operation # prints "delegate implementation"
end</lang>
=={{header|Tcl}}==
|