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);
List hobbies = new ArrayList();
hobbies.add("LOL");
hobbies.add("CF");
hobbies.add("CJ");
User user1 = User.builder().id(1).username("张三").password("1234").hobbies(hobbies).build();
System.out.println(user1);
}
示例3 :使用@Builder.Default
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; @Builder.Default private final String zipCode = "123456"; private String username; private String password; @Singular(value = "testHobbies") private List<String> hobbies; }
把zipCode 属性上加上注解@Builder.Default zipCode 这个值就可以改变。
测试方法:
User user2 = User.builder().id(1).zipCode("SSSS").username("张三").password("1234").testHobbies("CF").testHobbies("LOL").build();
System.out.println(user2);
总结:Builder 模式适用于当实体类的参数有多个,但是有很多参数不是必填的,@Singular,是用来向属性中添加集合的时候使用的。
本文部分转自: https://www.jianshu.com/p/d08e255312f9 作者讲的比较详细。