简体   繁体   中英

What pattern name is this?

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:

  • you can not check the objects to avoid null pointer exceptions(this is the biggest drawback IMO)
  • the methods will return 'this' object, which is counterintuitive(see setName in my example)
  • when returning other objects, like the ball object the readability of the code is decreased
  • when calling methods in the same row. it becomes a bit more difficult to debug because you put the breakpoint at the row where there could be 10 methods chained.

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