简体   繁体   English

为什么 Builder 设计模式中的 setter 方法会返回“this”?

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

I want to know why setter methods has return this;我想知道为什么 setter 方法会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. Builder 模式并不一定要求它必须是流利的,但这通常是它的实现方式。 It allows for users of the Builder to string together multiple calls (ie, "fluent"):它允许 Builder 的用户将多个调用串在一起(即“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?您会看到: 为什么强烈鼓励使用构建器模式,而不是在 Java 中直接实现流畅的 API? and Using fluent interface with builder pattern以及使用带有构建器模式的流畅界面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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