Skip to content

Instantly share code, notes, and snippets.

@ryanseys
Created October 10, 2015 19:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ryanseys/2bdaa97c854045498877 to your computer and use it in GitHub Desktop.
Builder pattern without a Builder class
public class Foo {
private String name;
private String town;
private int age;
public Foo setName(String name) {
this.name = name;
return this;
}
public Foo setTown(String town) {
this.town = town;
return this;
}
public Foo setAge(int age) {
this.age = age;
return this;
}
public String toString() {
return name + " from " + town + " aged " + age;
}
public static void main(String[] args) {
Foo f = new Foo()
.setName("Bob")
.setTown("Ottawa")
.setAge(23);
System.out.println(f); // Bob from Ottawa aged 23
f.setAge(34);
System.out.println(f); // Bob from Ottawa aged 34
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment