Skip to content

Instantly share code, notes, and snippets.

@breda
Created February 19, 2016 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breda/c00578d6ff235b37f608 to your computer and use it in GitHub Desktop.
Save breda/c00578d6ff235b37f608 to your computer and use it in GitHub Desktop.
Builder Example
public class Person {
/* Attributes */
protected String name;
protected String email;
protected int age;
protected String adress;
protected String job;
protected boolean married;
public Person(String name, String email, int age, String adress, String job, boolean married) {
this.name = name;
this.email = email;
this.age = age;
this.adress = adress;
this.job = job;
this.married = married;
}
/* Some getters and setters... */
}
/* Usage */
Person reda = new Person("Reda", "email@xxx.com", 40, "Somewhere", "Some Job", false);
import Person;
public clacc PersonBuilder {
/* Attributes */
protected String name;
protected String email;
protected int age;
protected String adress;
protected String job;
protected boolean married;
public PersonBuilder setName(String name) {
this.name = name;
return this;
}
public PersonBuilder setEmail(String email) {
this.email = email;
return this;
}
public PersonBuilder setAge(int age) {
this.age = age;
return this;
}
public PersonBuilder setAdress(String adress) {
this.adress = adress;
return this;
}
public PersonBuilder setJob(String job) {
this.job = job;
return this;
}
public PersonBuilder setMarried(boolean married) {
this.married = married;
return this;
}
/* Final step, return the actual Person instance. */
public Person make(void) {
return new Person(this.name, this.email, this.age, this.adress, this.job, this.married);
}
}
/* Usage — More readability */
Person reda = new PersonBuilder()
.setName("Reda")
.setEmail("email@xxx.com")
.setAge(40)
.setAdress("Somewhere")
.setJob("Some Job")
.setMarried(false)
.make();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment