Can one create an extensible class hierarchy in java whose methods are fluent and can be invoked in any order? (YES! see answer below), even for existing classes wh
I believe there is a way to do this with generics... Syntax is a little less clean than the desired...
Here is the client code...
B b = B.factoryB();
b.setA("a").setB("b");
A ba = A.factoryA();
ba.setA("a");
Top level (real) class
public class A extends Chained {
private String a = null;
protected A() {
}
public S setA(String a) {
this.a = a;
return me();
}
public static A factoryA() {
return new A();
}
}
Example Subclass
public class B extends A {
private String b = null;
B() {
}
public S setB(String b) {
this.b = b;
return me();
}
public static B factoryB() {
return new B();
}
}
Helper
public abstract class Chained {
// class should be extended like:
// ... class A extends Chained
public Chained() {
}
public final S me() {
return (S) this;
}
}
It's far from perfect and can be made not to work (if you really wanted to)