之前已经写过一篇通用Builder来构建实例对象的(基于Java8的新特性写一个通用的Builder工具类_java手动写一个builder-CSDN博客)但是这个builder不能构建集合,也就是list和map,今天突然心血来潮,想写写集合类的builder,这两个builder相比于通用的builder要简单易懂的多,废话不多说,直接上代码:
Mapbuilder:
public class MapBuilder<K, V> {
private Map<K, V> map;
private MapBuilder(Map<K, V> map) {
this.map = map;
}
public static <K, V> MapBuilder<K, V> ofMap() {
return new MapBuilder<>(new HashMap<K, V>());
}
public MapBuilder<K, V> put(K key, V value) {
this.map.put(key, value);
return this;
}
public Map<K, V> build() {
return this.map;
}
public static void main(String[] args) {
Map<String, Integer> map = MapBuilder.<String, Integer>ofMap()
.put("a", 1)
.put("b", 2)
.put("c", 3)
.build();
System.out.println(map); // 输出:{a=1, b=2, c=3}
}
}
ListBuilder:
public class ListBuilder<T> {
private List<T> list;
private ListBuilder(List<T> list) {
this.list = list;
}
public static <T> ListBuilder<T> ofList() {
return new ListBuilder(new ArrayList<T>());
}
public ListBuilder<T> add(T t) {
this.list.add(t);
return this;
}
public List<T> build() {
return this.list;
}
public static void main(String[] args) {
List<Integer> integers = ListBuilder.<Integer>ofList().add(1).build();
System.err.println(integers);
}
}