TypedBuilder

From APIDesign

Jump to: navigation, search

TBD

I need to write a builder for HTML DOM elements. Or rather React.js elements. How can we create a builder for all the difference elements without generating many Java classes? Here is an idea:

public abstract class ElemBuilder {
    ElemBuilder() {
    }
 
    public static <T extends ElemBuilder & Href<T> & ClassName<T>> T a() {
        return (T) new Impl("a");
    }
 
    public static <T extends ElemBuilder & ClassName<T>> T b() {
        return (T) new Impl("b");
    }
 
    public interface ClassName<T> {
        T className(String className);
    }
 
    public interface Href<T> {
        T href(String url);
    }
 
    private static final class Impl extends ElemBuilder 
    implements ClassName<ElemBuilder>, Href<ElemBuilder> {
        private final String name;
 
        private Impl(String name) {
            this.name = name;
        }
 
        @Override
        public ElemBuilder className(String className) {
            return this;
        }
 
        @Override
        public ElemBuilder href(String url) {
            return this;
        }
    }
}

The implementation of the builder Impl implements all the element interfaces, but each builder creating method - e.g. a or b - specify the attributes that are supported with the use of generics:

<T extends ElemBuilder & Href<T> & ClassName<T>>

as such the IDE provides reasonable code completion.

Personal tools