2d11f9d82646c1a3ea04a3e0818c2fe5c93f0664.svn-base 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package cn.com.goldenwater.dcproj.utils;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.function.Consumer;
  5. import java.util.function.Supplier;
  6. /**
  7. * 通用的 Builder 模式构建器
  8. *
  9. * @author: Lql
  10. * @since 2021/01/20
  11. */
  12. public class Builder<T> {
  13. private final Supplier<T> instantiator;
  14. private List<Consumer<T>> modifiers = new ArrayList<>();
  15. public Builder(Supplier<T> instantiator) {
  16. this.instantiator = instantiator;
  17. }
  18. public static <T> Builder<T> of(Supplier<T> instantiator) {
  19. return new Builder<>(instantiator);
  20. }
  21. public <P1> Builder<T> with(Consumer1<T, P1> consumer, P1 p1) {
  22. Consumer<T> c = instance -> consumer.accept(instance, p1);
  23. modifiers.add(c);
  24. return this;
  25. }
  26. public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
  27. Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
  28. modifiers.add(c);
  29. return this;
  30. }
  31. public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
  32. Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
  33. modifiers.add(c);
  34. return this;
  35. }
  36. public T build() {
  37. T value = instantiator.get();
  38. modifiers.forEach(modifier -> modifier.accept(value));
  39. modifiers.clear();
  40. return value;
  41. }
  42. /**
  43. * 1 参数 Consumer
  44. */
  45. @FunctionalInterface
  46. public interface Consumer1<T, P1> {
  47. void accept(T t, P1 p1);
  48. }
  49. /**
  50. * 2 参数 Consumer
  51. */
  52. @FunctionalInterface
  53. public interface Consumer2<T, P1, P2> {
  54. void accept(T t, P1 p1, P2 p2);
  55. }
  56. /**
  57. * 3 参数 Consumer
  58. */
  59. @FunctionalInterface
  60. public interface Consumer3<T, P1, P2, P3> {
  61. void accept(T t, P1 p1, P2 p2, P3 p3);
  62. }
  63. }