1、当构造方法参数过多时使用Builder模式,
import lombok.Builder; import lombok.Data; import lombok.ToString; @Builder(toBuilder = true) @ToString public class NutritionFacts { // Required parameters private final int servingSize; private final int servings; // Optional parameters - initialized to default values private int calories = 0; private int fat = 0; private int sodium = 0; private int carbohydrate = 0; }
测试方法:
@Test void testBuilder(){ NutritionFacts nutritionFacts = NutritionFacts.builder().calories(100).sodium(19).build(); System.out.println(nutritionFacts); }
示例2:@Builder和@Singular 一起使用
import lombok.Builder; import lombok.Data; import lombok.Singular; import lombok.ToString; import java.util.List; @Builder @ToString public class User { private final Integer id; private final String zipCode = "123456"; private String username; private String password; @Singular(value = "testHobbies") private List<String> hobbies; }
测试方法:
@Test void testUser(){ User user = User.builder().id(1).username("张三").password("1234").testHobbies("CF").testHobbies("LOL").build(); System.out.println(user); }
总结:Builder 模式适用于当实体类的参数有多个,但是有很多参数不是必填的,@Singular,是用来向属性中添加集合的时候使用的。
本文部分转自: https://www.jianshu.com/p/d08e255312f9