Is there a name for the Builder Pattern where the Builder is implemented via interfaces so certain parameters are required?
- by Zipper
So we implemented the builder pattern for most of our domain to help in understandability of what actually being passed to a constructor, and for the normal advantages that a builder gives. The one twist was that we exposed the builder through interfaces so we could chain required functions and unrequired functions to make sure that the correct parameters were passed. I was curious if there was an existing pattern like this.
Example below:
public class Foo
{
private int someThing;
private int someThing2;
private DateTime someThing3;
private Foo(Builder builder)
{
this.someThing = builder.someThing;
this.someThing2 = builder.someThing2;
this.someThing3 = builder.someThing3;
}
public static RequiredSomething getBuilder()
{
return new Builder();
}
public interface RequiredSomething { public RequiredDateTime withSomething (int value); }
public interface RequiredDateTime { public OptionalParamters withDateTime (DateTime value); }
public interface OptionalParamters {
public OptionalParamters withSeomthing2 (int value);
public Foo Build ();}
public static class Builder implements RequiredSomething, RequiredDateTime, OptionalParamters
{
private int someThing;
private int someThing2;
private DateTime someThing3;
public RequiredDateTime withSomething (int value) {someThing = value; return this;}
public OptionalParamters withDateTime (int value) {someThing = value; return this;}
public OptionalParamters withSeomthing2 (int value) {someThing = value; return this;}
public Foo build(){return new Foo(this);}
}
}
Example of how it's called:
Foo foo = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).build();
Foo foo2 = Foo.getBuilder().withSomething(1).withDateTime(DateTime.now()).withSomething2(3).build();