2

As far as I know about builder pattern, for example, an object, Student:

public class Student{
 private String name;
 private int age;
 //setter and getter
} 

to apply builder pattern to Student, StudentBuilder should be like this:

Version 1 : Set Student as an instance variable of StudentBuilder

public class StudentBuilder{
 private Student _student;
 public void setName(String name){
 this._student.setName(name);
 }
 public void setAge(int age){
 this._student.setAge(age);
 }
 public Student build(){
 return this._student;
 }
} 

However, after reading question and answer in this : https://softwareengineering.stackexchange.com/a/388062, as I know, the builder in the question uses the instance variables as parameters, like the following shows:

Version 2 : Set all the parameters of Student as instance variables of StudentBuilder first, finally new Student() and assign the instance variables of StudentBuilder to that new Student:

public class StudentBuilder{
 private String _name;
 private int _age;
 public void setName(String name){
 this._name=name;
 }
 public void setAge(int age){
 this._age(age);
 }
 public Student build(){
 Student student=new Student();
 student.setName(_name);
 student.setAge(_age);
 return student;
 }
} 

My question is, version 1 and version 2, which is the proper builder pattern?

asked Jun 24, 2024 at 6:40

1 Answer 1

2

My question is, version 1 and 2, which is the proper builder pattern?

Both versions are proper implementations of the builder pattern.

The builder pattern is characterized by how the client code interacts with the <N>Builder class/object, but how it achieves the desired result is an implementation detail that is deemed unimportant for the design pattern.

That said, version 1 is an unusual implementation, because when that version is possible, there is not really a reason to use the builder pattern in the first place.

The main motivation for the builder pattern is that you need to instantiate a class N that cannot be instantiated with partial information and either

  • the required information gradually becomes available and the builder pattern gives you an easy location to collect it all, or
  • you want to emulate something like named constructor parameters in a language that doesn't support them
answered Jun 24, 2024 at 7:06

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.