The key to the builder pattern is a static inner class which allows parameters to be set and the updated builder object returned.
The class to be built needs a single constructor that accepts the builder object:
public class ObjectWithOptionalParameters
{
private String name;
private int height;
private String flavour;
public ObjectWithOptionalParameters(Builder builder)
{
this.name = builder.name;
this.height = builder.height;
this.flavour = builder.flavour;
}
public static class Builder
{
private String name;
private int height;
private String flavour;
public Builder name(String name)
{
this.name = name;
return this;
}
public Builder height(int height)
{
this.height = height;
return this;
}
public Builder flavour(String flavour)
{
this.flavour = flavour;
return this;
}
public ObjectWithOptionalParameters build()
{
return new ObjectWithOptionalParameters(this);
}
}
}
{
private String name;
private int height;
private String flavour;
public ObjectWithOptionalParameters(Builder builder)
{
this.name = builder.name;
this.height = builder.height;
this.flavour = builder.flavour;
}
public static class Builder
{
private String name;
private int height;
private String flavour;
public Builder name(String name)
{
this.name = name;
return this;
}
public Builder height(int height)
{
this.height = height;
return this;
}
public Builder flavour(String flavour)
{
this.flavour = flavour;
return this;
}
public ObjectWithOptionalParameters build()
{
return new ObjectWithOptionalParameters(this);
}
}
}
Usage:
ObjectWithOptionalParameters myObj = ObjectWithOptionalParameters.Builder().name("Chris").height(190).flavour("Cherry").build();