简体   繁体   中英

Why do setter methods in the Builder design pattern return `this`?

I want to know why setter methods has return this; in it. What does it mean?

new Person().setName("alex");

That's called a "fluent" interface. The Builder pattern doesn't necessarily dictate that it has to be fluent, but that's often how it's implemented. It allows for users of the Builder to string together multiple calls (ie, "fluent"):

Persoon al = Person.builder()
            .setFirstName("Albert")
            .setLastName("Einstein")
            .setOccupation("Genius")
            .setGender(Gender.Male)
            .build();

As already answered, it's not necessary, but it is the convention. And by using it, you can take advantage of the method chaining (Note that method chaining eliminates an extra variable for each intermediate step). You can see: Why is the usage of builder pattern highly encouraged instead of a straight forward implementation of fluent API in Java? and Using fluent interface with builder pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM