Skip to content

Instantly share code, notes, and snippets.

@cbeams
Created May 16, 2011 13:17
Show Gist options
  • Save cbeams/974426 to your computer and use it in GitHub Desktop.
Save cbeams/974426 to your computer and use it in GitHub Desktop.
Flexible Polymorphic Method Chaining
/**
* Demonstrates a pattern for generic signatures in abstract base classes
* allowing for a method chaining API that is not dependent on order of method
* invocation: the concrete type (C in the case below) is always returned from
* every method that returns the generic parameter T.
*
* While the generic signatures are complex, using the concrete type C remains
* very simple. This tradeoff allows for the design of easy-to-use 'builder
* style' APIs.
*
* @author Chris Beams
*/
public class FlexiblePolymorphicMethodChaining {
public static void main(String... args) {
new C()
.a() // note that invocation order
.b() // does not matter. the most
.c() // specific type (C) is always
.b() // returned, meaning that all
.a() // methods in the inheritance
.c() // hierarchy are always available.
;
}
}
abstract class A<T extends A<T>> {
@SuppressWarnings("unchecked")
protected T instance = (T) this;
T a() {
return this.instance;
}
}
abstract class B<T extends B<T>> extends A<T> {
T b() {
return this.instance;
}
}
class C extends B<C> {
C c() {
return this.instance;
}
}
@albert-kam
Copy link

Good Example ! One question: If class B were a concrete class, how does one initiate class B as new B<B>() doesnt work ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment