samedi 30 janvier 2016

Limiting Builder Pattern Parameter

I have simple builder example to illustrate the question "How can I stop a builder parameter from being set twice?"

SimpleVehicle kia = new SimpleVehicle.Builder().setPrice(100).setType("Kia").setPrice(120).build();

System.out.println(kia.toString());

The price has been set to 100 and then again to 120. Is it possible to prevent this? The print returns - SimpleVehicle{price=120, type='Kia'} which is what the builder was asked to do.

The SimpleVehicle class is

public class SimpleVehicle {

private long price;
private String type;

private SimpleVehicle(Builder builder) {
    this.price = builder.price;
    this.type = builder.type;
}

@Override
public String toString() {
    return "SimpleVehicle{" +
            "price=" + price +
            ", type='" + type + '\'' +
            '}';
}

public static class Builder {

    private long price;
    private String type;

    public Builder(){

    }

    public Builder setPrice(long value) {
        this.price = value;
        return this;
    }

    public Builder setType(String value) {
        this.type = value;
        return this;
    }

    public SimpleVehicle build() {
        return new SimpleVehicle(this);
    }

}

}

Aucun commentaire:

Enregistrer un commentaire