Home  >  Article  >  Java  >  A detailed introduction to the Builder mode in Java to build MAP/LIST

A detailed introduction to the Builder mode in Java to build MAP/LIST

黄舟
黄舟Original
2017-10-09 10:14:431871browse

The following editor will bring you an example of how to build MAP/LIST in Java Builder mode. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let's follow the editor and take a look.

When we build a MAP, we have to call put constantly. Sometimes it seems very troublesome. Just so I looked at the builder mode and thought this idea is good, so Ever since, I wrote an example of building MAP using builder mode,

The code is as follows:


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));
 }
}

The above is the detailed content of A detailed introduction to the Builder mode in Java to build MAP/LIST. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn