New page: 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 clas...
New page
[[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:
<source lang="java">
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;
}
}
}
</source>
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:
<source lang="java">
<T extends ElemBuilder & Href<T> & ClassName<T>>
</source>
as such the IDE provides reasonable code completion.
[[Category:APIDesignPatterns]]
[[Category:APIDesignPatterns:Creational]]
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:
<source lang="java">
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;
}
}
}
</source>
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:
<source lang="java">
<T extends ElemBuilder & Href<T> & ClassName<T>>
</source>
as such the IDE provides reasonable code completion.
[[Category:APIDesignPatterns]]
[[Category:APIDesignPatterns:Creational]]