码迷,mamicode.com
首页 > 编程语言 > 详细

Java 8 consumer风格Builder

时间:2020-07-01 20:28:06      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:icon   lis   object   etag   bic   clear   ant   return   function   

 1 public static class GenericBuilder<T> {
 2         private final Supplier<T> instantiate;
 3 
 4         private final List<Consumer<T>> consumers = new ArrayList<>();
 5 
 6         public GenericBuilder(Supplier<T> instantiate) {
 7             this.instantiate = instantiate;
 8         }
 9 
10         public static <T> GenericBuilder<T> of(Supplier<T> instantiator)  {
11             return new GenericBuilder<>(instantiator);
12         }
13 
14         public <U> GenericBuilder<T> with(BiConsumer<T, U> biConsumer, U value) {
15             Consumer<T> setOperationFunction = instance -> biConsumer.accept(instance, value);
16             consumers.add(setOperationFunction);
17             return this;
18         }
19 
20         public T build() {
21             T instance = instantiate.get();
22 
23             // loop call each set function with object instance!
24             consumers.forEach(consumer -> consumer.accept(instance));
25             consumers.clear();
26 
27             return instance;
28         }
29     }

 

使用:

 

 1 public class Dummy {
 2         private String name;
 3         private Integer age;
 4         private Boolean foreigner;
 5 
 6         public String getName() {
 7             return name;
 8         }
 9 
10         public void setName(String name) {
11             this.name = name;
12         }
13 
14         public Integer getAge() {
15             return age;
16         }
17 
18         public void setAge(Integer age) {
19             this.age = age;
20         }
21 
22         public Boolean getForeigner() {
23             return foreigner;
24         }
25 
26         public void setForeigner(Boolean foreigner) {
27             this.foreigner = foreigner;
28         }
29 
30 
31     }

 

Dummy build = GenericBuilder.of(Dummy::new).with(Dummy::setAge, 12)
                .with(Dummy::setName, "Vodoo")
                .with(Dummy::setForeigner, false).build();

 

Java 8 consumer风格Builder

标签:icon   lis   object   etag   bic   clear   ant   return   function   

原文地址:https://www.cnblogs.com/Joynic/p/13220858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!