Java和C ++中的构建器? [英] Builders in Java versus C++?

查看:144
本文介绍了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.

这篇关于Java和C ++中的构建器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆