About the pattern sampled below, do anyone knows it's name or creator? It seem a variation of Builder proposed by GoF.( https://en.wikipedia.org/wiki/Builder_pattern#Java )
I think it achieve the main goal of the GoF pattern with much less code. I saw in some framework and started using it a lot, but can't find it's proporser. Thanks for the help.
public class User {
private String name;
public User name(String name) {
setName(name);
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I would go for this, to avoid an error for having the same name for member and method:
public class User {
private String name;
public String getName() {
return name;
}
public User setName(String name) {
this.name = name;
return this;
}
}
User user = (new User()).setName('Me').setPhone('1234');
It seems the name of the pattern is 'fluent interface', while 'method chaining' is called its implementation of chaining methods. Practically, they describe the same thing but 'fluent interface' was the name generally accepted for the pattern.
You can chain more methods(not only for setting properties) including different objects:
user.addBall(ball)
.inflateAllBalls()
.getFirstBall() // returns a ball
.roll() // roll is a method in the Ball class
.setColor("red");
The cons of overusing method chaining:
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.