我们在构建一个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));
} }
代码很简单,甚至都不用特殊说明,但里面的知识点还是蛮多的,比如builder模式,比如泛型的使用。
大家可以在项目中试用一下,能使代码更加的简洁漂亮!