我们在构建一个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的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

02-03 08:41