When using the builder pattern in C++, is it advisable for the setters to return a reference to the builder object?
I am thinking of using the builder pattern in C++ unit tests, to streamline the creation of input data for the code being tested.
In Java the common idiom s开发者_Python百科eems to be to have the setters of the builder class return the (reference to) the builder object itself, so that multiple setters can be chained in a single line. E. g. the builder class could be defined like this:
// class builder
public class Builder
{
private Part1 part1;
private Part2 part2;
public Builder withPart1(Part1 p1);
public Builder withPart2(Part2 p2);
};
And then used like this:
Builder b;
Part1 p1;
Part2 p2;
b.withPart1(p1).withPart2(p2);
The same effect can be achieved in C++ by having the setters return a reference to the builder object. However, I have not been able to find any examples of that on the web. Is this kind of "chaining" a common practice in C++? And if no, then why not?
Yes it's a common practice, it's called a "Fluent API".
The canonical example:
while ((std::cin >> std::setbase(16) >> i >> s).getline(s2)) { ... }
精彩评论