简体   繁体   English

lombok @Builder vs构造函数

[英]lombok @Builder vs constructor

I'm quite new to java. 我对java很新。 Could someone explain me the advantages of using lombok @Builder to create an object instead of constructor call? 有人能解释我使用的优势, lombok @Builder创建一个对象,而不是构造函数调用?

MyObject o1 = MyObject.builder()
              .id(1)
              .name("name")
              .build();

MyObject o2 = new MyObject(1, "name")

Is it just a question of better visibility? 这只是一个更好的可见度问题吗?

Consider: 考虑:

Order order = new Order("Alan", "Smith", 2, 6, "Susan", "Smith");

What do the parameters mean? 参数是什么意思? We have to look at the constructor spec to find out. 我们必须查看构造函数规范才能找到答案。

Now with a builder: 现在有了一个建设者:

Order order = Order.builder()
    .originatorFirstName("Alan")
    .originatorLastName("Smith")
    .lineItemNumber(2)
    .quantity(6)
    .recipientFirstName("Susan")
    .recipientLastName("Smith")
    .build();

It's more wordy, but it's very clear to read, and with IDE assistance it's easy to write too. 它更加冗长,但阅读非常清楚,并且在IDE的帮助下,它也很容易编写。 The builders themselves are a bit of a chore to write, but code-generation tools like Lombok help with that. 构建器本身是一件苦差事,但像Lombok这样的代码生成工具对此有所帮助。

Some people argue that if your code needs builders to be readable, that's exposing other smells. 有些人认为,如果你的代码需要构建器可读,那就暴露出其他气味。 You're using too many basic types; 你使用的基本类型太多了; you're putting too many fields in one class. 你在一个班级里放了太多的田地。 For example, consider: 例如,考虑:

Order order = new Order(
     new Originator("Alan", "Smith"),
     new ItemSet(new Item(2), 6),
     new Recipient("Susan", "Smith"));

... which is self-explanatory without using a builder, because we are using more classes with single-responsibilities and fewer fields. ......不使用构建器,这是不言自明的,因为我们使用的是更多具有单一职责和更少字段的类。

This is not a lombok specific feature, this is called a builder pattern. 这不是一个特定于lombok的功能,这称为构建器模式。

Imagine you have a class with 20 parameters, and 10 of them are optional. 想象一下,你有一个包含20个参数的类,其中10个是可选的。 You could somehow make tons of constructors taking care of this logic, or make a constructor with all those arguments and pass nulls in some places. 您可以以某种方式使大量构造函数处理此逻辑,或者使用所有这些参数创建构造函数并在某些位置传递null。 Isn't builder pattern simply easier? 构建器模式不简单吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM