Publications: 82 | Followers: 0

Build Pattern - courses.cs.vt.edu

Publish on Category: Birds 0

Builder Pattern
What’s Builder: TO find a solution to the telescoping constructorProblem: Too many parametersSolution: To get an abstract object, a builder, that receives each initialization parameter step by step andthenreturns the resulting constructed object at once
Example
publicclassUser {privatefinalStringfirstName;    //requiredprivatefinalStringlastName;    //requiredprivatefinalintage;    //optionalprivatefinalString phone;    //optionalprivatefinalString address;    //optional}
Option One
publicUser(StringfirstName, StringlastName) {this(firstName,lastName, 0);}publicUser(StringfirstName, StringlastName,intage) {this(firstName,lastName, age, '');}publicUser(StringfirstName, StringlastName,intage, String phone) {this(firstName,lastName, age, phone, '');}publicUser(StringfirstName, StringlastName,intage, String phone, String address) {this.firstName=firstName;this.lastName=lastName;this.age= age;this.phone= phone;this.address= address;}
Option Two
publicclassUser {privateStringfirstName; // requiredprivateStringlastName; // requiredprivateintage; // optionalprivateString phone; // optionalprivateString address;  //optionalpublicStringgetFirstName() {returnfirstName;}publicvoidsetFirstName(StringfirstName) {this.firstName=firstName;}publicStringgetLastName() {returnlastName;}publicvoidsetLastName(StringlastName) {this.lastName=lastName;}
publicvoidsetAge(intage) {this.age= age;}publicStringgetPhone() {returnphone;}publicvoidsetPhone(String phone) {this.phone= phone;}publicStringgetAddress() {returnaddress;}publicvoidsetAddress(String address) {this.address= address;}}
Option Three
publicclassUser {privatefinalStringfirstName; // requiredprivatefinalStringlastName; // requiredprivatefinalintage; // optionalprivatefinalString phone; // optionalprivatefinalString address; // optionalprivateUser(UserBuilderbuilder) {this.firstName=builder.firstName;this.lastName=builder.lastName;this.age=builder.age;this.phone=builder.phone;this.address=builder.address;}
publicStringgetFirstName() {returnfirstName;}publicStringgetLastName() {returnlastName;}publicintgetAge() {returnage;}
publicStringgetPhone() {returnphone;}publicStringgetAddress() {returnaddress;}
publicstaticclassUserBuilder{privatefinalStringfirstName;privatefinalStringlastName;privateintage;privateString phone;privateString address;publicUserBuilder(StringfirstName, StringlastName) {this.firstName=firstName;this.lastName=lastName;}
publicUserBuilderage(intage) {this.age= age;returnthis;}publicUserBuilderphone(String phone) {this.phone= phone;returnthis;}publicUserBuilderaddress(String address) {this.address= address;returnthis;}publicUser build() {returnnewUser(this);}
publicUsergetUser() {returnnewUser.UserBuilder('Jhon', 'Doe').age(30).phone('1234567').address('Fake address 1234').build();}

0

Embed

Share

Upload

Make amazing presentation for free
Build Pattern - courses.cs.vt.edu