Java与C ++的构建者? [英] Builders in Java versus C++?
问题描述
在Google的 Protocol Buffer API for Java中,他们使用这些漂亮的Builders创建一个对象(请参见 here ):
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(请参阅 here )
But the corresponding C++ API does not use such Builders (see here)
C ++和Java API是应该做同样的事情,所以我想知道为什么他们也不使用C ++中的构建器。有没有背后的语言原因,即它不是惯用的,还是在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.
这篇关于Java与C ++的构建者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!