通过Builder定义

    1. /**
    2. * 通用的 Builder 模式构建器
    3. *
    4. * @author: xq
    5. * @since 2019/8/29
    6. */
    7. public class Builder<T> {
    8. private final Supplier<T> instantiator;
    9. private List<Consumer<T>> modifiers = new ArrayList<>();
    10. public Builder(Supplier<T> instantiator) {
    11. this.instantiator = instantiator;
    12. }
    13. public static <T> Builder<T> of(Supplier<T> instantiator) {
    14. return new Builder<>(instantiator);
    15. }
    16. public <P1> Builder<T> with(Consumer1<T, P1> consumer, P1 p1) {
    17. Consumer<T> c = instance -> consumer.accept(instance, p1);
    18. modifiers.add(c);
    19. return this;
    20. }
    21. public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
    22. Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
    23. modifiers.add(c);
    24. return this;
    25. }
    26. public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
    27. Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
    28. modifiers.add(c);
    29. return this;
    30. }
    31. public T build() {
    32. T value = instantiator.get();
    33. modifiers.forEach(modifier -> modifier.accept(value));
    34. modifiers.clear();
    35. return value;
    36. }
    37. /**
    38. * 1 参数 Consumer
    39. */
    40. @FunctionalInterface
    41. public interface Consumer1<T, P1> {
    42. void accept(T t, P1 p1);
    43. }
    44. /**
    45. * 2 参数 Consumer
    46. */
    47. @FunctionalInterface
    48. public interface Consumer2<T, P1, P2> {
    49. void accept(T t, P1 p1, P2 p2);
    50. }
    51. /**
    52. * 3 参数 Consumer
    53. */
    54. @FunctionalInterface
    55. public interface Consumer3<T, P1, P2, P3> {
    56. void accept(T t, P1 p1, P2 p2, P3 p3);
    57. }
    58. }
    1. import lombok.Data;
    2. /**
    3. * @author xq
    4. * @date 2022/05/27 15:50
    5. * @describe
    6. */
    7. @Data
    8. public class Cat {
    9. private String name;
    10. private Integer age;
    11. }
    12. /**
    13. * @author xq
    14. * @date 2022/05/27 15:50
    15. * @describe
    16. */
    17. public class Test {
    18. @SneakyThrows
    19. public static void main(String[] args) {
    20. Cat cat = Builder.of(Cat::new)
    21. .with(Cat::setName, "name")
    22. .with(Cat::setAge, 2)
    23. .build();
    24. }
    25. }