Delegates: Difference between revisions

2,305 bytes added ,  10 years ago
Added Java 8 version of the original example
(Added zkl)
(Added Java 8 version of the original example)
Line 788:
assert a.operation().equals("anonymous delegate implementation");
}
}</lang>
 
{{works with|Java|8+}}
<lang java>package delegate;
 
@FunctionalInterface
public interface Thingable {
public String thing();
}</lang>
 
<lang java>package delegate;
 
import java.util.Optional;
 
public interface Delegator {
public Thingable delegate();
public Delegator delegate(Thingable thingable);
 
public static Delegator new_() {
return $Delegator.new_();
}
public default String operation() {
return Optional.ofNullable(delegate())
.map(Thingable::thing)
.orElse("default implementation")
;
}
}</lang>
 
<lang java>package delegate;
 
@FunctionalInterface
/* package */ interface $Delegator extends Delegator {
@Override
public default Delegator delegate(Thingable thingable) {
return new_(thingable);
}
 
public static $Delegator new_() {
return new_(() -> null);
}
 
public static $Delegator new_(Thingable thingable) {
return () -> thingable;
}
}</lang>
 
<lang java>package delegate;
 
public final class Delegate implements Thingable {
@Override
public String thing() {
return "delegate implementation";
}
}</lang>
 
<lang java>package delegate;
 
// Example usage
// Memory management ignored for simplification
public interface DelegateTest {
public static String thingable() {
return "method reference implementation";
}
 
public static void main(String... arguments) {
// Without a delegate:
Delegator d1 = Delegator.new_();
assert d1.operation().equals("default implementation");
 
// With a delegate:
Delegator d2 = d1.delegate(new Delegate());
assert d2.operation().equals("delegate implementation");
 
// Same as the above, but with an anonymous class:
Delegator d3 = d2.delegate(new Thingable() {
@Override
public String thing() {
return "anonymous delegate implementation";
}
});
assert d3.operation().equals("anonymous delegate implementation");
 
// Same as the above, but with a method reference:
Delegator d4 = d3.delegate(DelegateTest::thingable);
assert d4.operation().equals("method reference implementation");
 
// Same as the above, but with a lambda expression:
Delegator d5 = d4.delegate(() -> "lambda expression implementation");
assert d5.operation().equals("lambda expression implementation");
}
}</lang>