我们在构建一个MAP时,要不停的调用put,有时候看着觉得很麻烦,刚好,看了下builder模式,觉得这思路不错,于是乎,照着用builder模式写了一个构建MAP的示例,
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import java.util.HashMap; import java.util.Map; public Builder< T > b; public MapBuilder(Builder< T > b){ this.b = b; } public Map< String ,T> map(){ return b.map; } public T get(String key){ return b.map.get(key); } public static class Builder< T >{ public Map< String , T> map; public Builder(){ map = new HashMap< String , T>(); } public Builder< T > map(String key, T value){ map.put(key, value); return this; } public MapBuilder< T > build(){ return new MapBuilder< T >(this); } } public static void main(String[] args) { MapBuilder< String > build = new MapBuilder.Builder< String >().map("a", "b").build(); System.out.println(build.get("a")); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public class ListBuilder< T > { public Builder< T > b; public ListBuilder(Builder< T > b){ this.b = b; } public List< T > list(){ return b.list; } public T get(int index){ return b.list.get(index); } public static class Builder< T >{ public List< T > list; public Builder(){ list = new ArrayList< T >(); } public Builder< T > add(T value){ list.add(value); return this; } public ListBuilder< T > build(){ return new ListBuilder< T >(this); } } public static void main(String[] args) { ListBuilder< String > build = new ListBuilder.Builder< String >().add("a").add("b").build(); System.out.println(build.get(0)); } } |
以上这篇Java Builder模式构建MAP/LIST的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/zhangfei/p/5124303.html