Java和C ++中的构建器?
在Google的 Protocol Buffer API for Java中,他们使用这些不错的Builders创建一个对象(见此处):
In Google's Protocol Buffer API for Java, they use these nice Builders that create an object (see here):
Person john =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe@example.com")
.addPhone(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
但是相应的C ++ API不使用这样的Builders(参见这里)
But the corresponding C++ API does not use such Builders (see here)
C ++和Java API应该是同样的事情,所以我想知道为什么他们不使用C ++中的构建器。有背后的语言原因,即它不是惯用的或它在C ++中皱眉?
The C++ and the Java API are supposed to be doing the same thing, so I'm wondering why they didn't use builders in C++ as well. Are there language reasons behind that, i.e. it's not idiomatic or it's frowned upon in C++? Or probably just the personal preference of the person who wrote the C++ version of Protocol Buffers?
正确的方式来实现类似的协议缓冲区在C ++中使用setter返回一个引用* this。
The proper way to implement something like that in C++ would use setters that return a reference to *this.
class Person {
std::string name;
public:
Person &setName(string const &s) { name = s; return *this; }
Person &addPhone(PhoneNumber const &n);
};
类可以像这样使用,假设类似定义PhoneNumber:
The class could be used like this, assuming similarly defined PhoneNumber:
Person p = Person()
.setName("foo")
.addPhone(PhoneNumber()
.setNumber("123-4567"));
如果需要单独的构建器类,那么也可以这样做。这样的构建器应该被分配
,当然。
If a separate builder class is wanted, then that can be done too. Such builders should be allocated in stack, of course.