Skip to content

Instantly share code, notes, and snippets.

@zcox
Created October 1, 2011 21:13
Show Gist options
  • Save zcox/1256666 to your computer and use it in GitHub Desktop.
Save zcox/1256666 to your computer and use it in GitHub Desktop.
Typesafe fluent interface subclass in Java
public class ABTest {
public static void main(String[] args) {
A<String> a = new A<String>().f1().f2();
B<String> b = new B<String>().f1().f2().f3();
System.out.println(a + " " + b);
}
/** The type parameter T just shows we can parameterize these types. */
public static class A<T> {
/** Creates and returns a new A instance. Only meant to be called by other methods internally.
* Subclasses should override and return a new instance of the subclass. */
protected A<T> create() {
return new A<T>();
}
/** Returns a new instance that is the combination of this instance and the f1 operation. */
public A<T> f1() {
return create(); //real impl would do other f1 stuff...
}
/** Returns a new instance that is the combination of this instance and the f2 operation. */
public A<T> f2() {
return create(); //real impl would do other f2 stuff...
}
}
/** The type parameter T just shows we can parameterize these types. */
public static class B<T> extends A<T> {
/** Overriden so that A methods will be using a new B instance. */
@Override
protected B<T> create() {
return new B<T>();
}
/** Overriden to return a B instead of an A. */
@Override
public B<T> f1() {
return (B<T>) super.f1(); //cast is safe because super.f1() will call create()
}
/** Overriden to return a B instead of an A. */
@Override public B<T> f2() { return (B<T>) super.f2(); }
/** Returns a new instance that is the combination of this instance and the f3 operation. */
public B<T> f3() {
return create(); //real impl would do other f3 stuff...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment