Design Pattern Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 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