Created
February 19, 2016 14:08
-
-
Save breda/c00578d6ff235b37f608 to your computer and use it in GitHub Desktop.
Builder Example
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 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 protected]", 40, "Somewhere", "Some Job", false); |
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
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 protected]") | |
.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