0% found this document useful (0 votes)
39 views

Design Pattern Java

The Builder pattern in Java allows object creation with a fluent and readable syntax by having each setter method return the object itself. This allows method calls to be chained together, making the code more concise and expressive. An example PersonBuilder class demonstrates how each set method returns the PersonBuilder, allowing a Person to be constructed by chaining setFirstName, setLastName, setAge before build() creates the final Person object.

Uploaded by

aashishduck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Design Pattern Java

The Builder pattern in Java allows object creation with a fluent and readable syntax by having each setter method return the object itself. This allows method calls to be chained together, making the code more concise and expressive. An example PersonBuilder class demonstrates how each set method returns the PersonBuilder, allowing a Person to be constructed by chaining setFirstName, setLastName, setAge before build() creates the final Person object.

Uploaded by

aashishduck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Design Pattern Java

In Java, a class in which every set method returns its object is known as a "Builder" or "Fluent Builder" pattern.
This pattern is often used for creating objects with a fluent and readable syntax. It allows you to chain method
calls together, which can make your code more concise and expressive.

Here's an example of a class following the Fluent Builder pattern:

```java
public class PersonBuilder {
private String firstName;
private String lastName;
private int age;

public PersonBuilder setFirstName(String firstName) {


this.firstName = firstName;
return this;
}

public PersonBuilder setLastName(String lastName) {


this.lastName = lastName;
return this;
}

public PersonBuilder setAge(int age) {


this.age = age;
return this;
}

public Person build() {


return new Person(firstName, lastName, age);
}
}
```

With this builder pattern, you can create a `Person` object like this:

```java
Person person = new PersonBuilder()
.setFirstName("John")
.setLastName("Doe")
.setAge(30)
.build();
```

This code allows you to set the properties of the `Person` object in a fluent manner using the `set` methods, and
then you call `build()` to create the final `Person` object.

You might also like