T - the type of instances to build.B - the type of builder subclass.public abstract class AbstractSupplier<T,B extends AbstractSupplier<T,B>> extends Object implements IOSupplier<T>
T.
Extend this class to implement the builder pattern.
For example, here is a builder, a domain class, and a test.
The builder:
/**
* Builds Foo instances.
*/
public static class Builder extends AbstractSupplier<Foo, Builder> {
private String bar1;
private String bar2;
private String bar3;
/**
* Builds a new Foo.
*/
@Override
public Foo get() {
return new Foo(bar1, bar2, bar3);
}
public Builder setBar1(final String bar1) {
this.bar1 = bar1;
return this;
}
public Builder setBar2(final String bar2) {
this.bar2 = bar2;
return this;
}
public Builder setBar3(final String bar3) {
this.bar3 = bar3;
return this;
}
}
The domain class:
/**
* Domain class.
*/
public class Foo {
public static Builder builder() {
return new Builder();
}
private final String bar1;
private final String bar2;
private final String bar3;
private Foo(final String bar1, final String bar2, final String bar3) {
this.bar1 = bar1;
this.bar2 = bar2;
this.bar3 = bar3;
}
public String getBar1() {
return bar1;
}
public String getBar2() {
return bar2;
}
public String getBar3() {
return bar3;
}
}
The test:
@Test
public void test() {
final Foo foo = Foo.builder()
.setBar1("value1")
.setBar2("value2")
.setBar3("value3")
.get();
assertEquals("value1", foo.getBar1());
assertEquals("value2", foo.getBar2());
assertEquals("value3", foo.getBar3());
}
| Constructor and Description |
|---|
AbstractSupplier()
Constructs a new instance for subclasses.
|
| Modifier and Type | Method and Description |
|---|---|
protected B |
asThis()
Returns this instance typed as the subclass type
B. |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitasSupplier, get, getUncheckedpublic AbstractSupplier()
protected B asThis()
B.
This is the same as the expression:
(B) this
B.