|
21 | 21 |
|
22 | 22 | /** |
23 | 23 | * Abstracts supplying an instance of {@code T}. Use to implement the builder pattern. |
| 24 | + * <p> |
| 25 | + * For example, here is a builder, a domain class, and a test. |
| 26 | + * </p> |
| 27 | + * <p> |
| 28 | + * The builder: |
| 29 | + * </p> |
| 30 | + * <pre> |
| 31 | + ∕** |
| 32 | + * Builds Foo instances. |
| 33 | + *∕ |
| 34 | + public static class Builder extends AbstractSupplier<Foo, Builder> { |
| 35 | +
|
| 36 | + private String bar1; |
| 37 | + private String bar2; |
| 38 | + private String bar3; |
| 39 | +
|
| 40 | + ∕** |
| 41 | + * Builds a new Foo. |
| 42 | + *∕ |
| 43 | + @Override |
| 44 | + public Foo get() { |
| 45 | + return new Foo(bar1, bar2, bar3); |
| 46 | + } |
| 47 | +
|
| 48 | + public Builder setBar1(final String bar1) { |
| 49 | + this.bar1 = bar1; |
| 50 | + return this; |
| 51 | + } |
| 52 | +
|
| 53 | + public Builder setBar2(final String bar2) { |
| 54 | + this.bar2 = bar2; |
| 55 | + return this; |
| 56 | + } |
| 57 | +
|
| 58 | + public Builder setBar3(final String bar3) { |
| 59 | + this.bar3 = bar3; |
| 60 | + return this; |
| 61 | + } |
| 62 | + } |
| 63 | + * </pre> |
| 64 | + * <p> |
| 65 | + * The domain class: |
| 66 | + * </p> |
| 67 | + * <pre> |
| 68 | + ∕** |
| 69 | + * Domain class. |
| 70 | + *∕ |
| 71 | + public class Foo { |
| 72 | +
|
| 73 | + public static Builder builder() { |
| 74 | + return new Builder(); |
| 75 | + } |
| 76 | +
|
| 77 | + private final String bar1; |
| 78 | + private final String bar2; |
| 79 | + private final String bar3; |
| 80 | +
|
| 81 | + private Foo(final String bar1, final String bar2, final String bar3) { |
| 82 | + this.bar1 = bar1; |
| 83 | + this.bar2 = bar2; |
| 84 | + this.bar3 = bar3; |
| 85 | + } |
| 86 | +
|
| 87 | + public String getBar1() { |
| 88 | + return bar1; |
| 89 | + } |
| 90 | +
|
| 91 | + public String getBar2() { |
| 92 | + return bar2; |
| 93 | + } |
| 94 | +
|
| 95 | + public String getBar3() { |
| 96 | + return bar3; |
| 97 | + } |
| 98 | +
|
| 99 | + } |
| 100 | + * </pre> |
| 101 | + * <p> |
| 102 | + * The test: |
| 103 | + * </p> |
| 104 | + * <pre> |
| 105 | + @Test |
| 106 | + public void test() { |
| 107 | + final Foo foo = Foo.builder() |
| 108 | + .setBar1("value1") |
| 109 | + .setBar2("value2") |
| 110 | + .setBar3("value3") |
| 111 | + .get(); |
| 112 | + assertEquals("value1", foo.getBar1()); |
| 113 | + assertEquals("value2", foo.getBar2()); |
| 114 | + assertEquals("value3", foo.getBar3()); |
| 115 | + } |
| 116 | + * </pre> |
24 | 117 | * |
25 | 118 | * @param <T> the type of instances to build. |
26 | 119 | * @param <B> the type of builder subclass. |
|
0 commit comments