下面小编就为大家带来一篇Java Builder模式构建MAP/LIST的实例讲解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
我们在构建一个MAP时,要不停的调用put,有时候看着觉得很麻烦,刚好,看了下builder模式,觉得这思路不错,于是乎,照着用builder模式写了一个构建MAP的示例,
代码如下:
import java.util.HashMap; import java.util.Map; public class MapBuilder<T> { 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")); } }
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)); } }
Atas ialah kandungan terperinci Java中Builder模式构建MAP/LIST的具体介绍. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!