Created
October 10, 2015 19:54
-
-
Save ryanseys/2bdaa97c854045498877 to your computer and use it in GitHub Desktop.
Builder pattern without a Builder class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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