下面小編就為大家帶來一篇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)); } }
以上是Java中Builder模式建構MAP/LIST的具體介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!