Delegates: Difference between revisions

1,545 bytes added ,  15 years ago
added java
(added perl, hope it's right)
(added java)
Line 148:
> delegator.operation()
# value: "default implementation"
 
=={{header|Java}}==
This implementation uses an interface called Thingable to specify the type of delegates that respond to thing(). The downside is that any delegate you want to use has to explicitly declare to implement the interface. The upside is that the type system guarantees that whent the delegate is non-null, it must implement the "thing" method.
 
<lang java>interface Thingable {
String thing();
}
 
class Delegator {
public Thingable delegate;
 
public String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
 
class Delegate implements Thingable {
public String thing() {
return "delegate implementation";
}
}
 
// Example usage
// Memory management ignored for simplification
public class DelegateExample {
public static void main(String[] args) {
// Without a delegate:
Delegator a = new Delegator();
assert a.operation().equals("default implementation");
 
// With a delegate:
Delegate d = new Delegate();
a.delegate = d;
assert a.operation().equals("delegate implementation");
 
// Same as the above, but with an anonymous class:
a.delegate = new Thingable() {
public String thing() {
return "anonymous delegate implementation";
}
};
System.out.println(a.operation());
assert a.operation().equals("anonymous delegate implementation");
}
}</lang>
 
=={{header|JavaScript}}==
Anonymous user