Skip to content

Instantly share code, notes, and snippets.

@DavidTPate
Created February 16, 2014 22:24
Show Gist options
  • Select an option

  • Save DavidTPate/9041496 to your computer and use it in GitHub Desktop.

Select an option

Save DavidTPate/9041496 to your computer and use it in GitHub Desktop.
An example of the Builder Pattern in Java for a simple car class.
public class Car {
int year;
String make;
String model;
String carType;
public static class Builder {
int year;
String make;
String model;
String carType;
public Builder year(int year) {
this.year = year;
return this;
}
public Builder make(String make) {
this.make = make;
return this;
}
public Builder model(String model) {
this.model = model;
return this;
}
public Builder carType(String carType) {
this.carType = carType;
return this;
}
public Car build() {
return new Car(this);
}
}
private Car(Builder builder) {
this.year = builder.year;
this.make = builder.make;
this.model = builder.model;
this.carType = builder.carType;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment