Builder模式適用於構造對象時,須要多個參數的狀況。對於多個參數,用方法名也能很好的說明用途。
java
但爲了構造對象,就必須先建立它的Builder構建器,在某些十分注重性能的狀況下,就多是一個性能問題。ide
實現方式1:性能
public class Book { private final String author; //必須參數 private final String name; //必須參數 private final String ISBN; //必須參數 private final String language; //非必須參數 private final int weight; //非必須參數 private Book(Builder builder){ author = builder.author; name = builder.name; ISBN = builder.ISBN; language = builder.language; weight = builder.weight; } public static class Builder{ private final String author; private final String name; private final String ISBN; private String language; private int weight; public Builder(String author, String name, String iSBN) { this.author = author; this.name = name; ISBN = iSBN; } public Builder language(String language){ this.language = language; return this; } public Builder weight(int weight){ this.weight = weight; return this; } public Book build(){ return new Book(this); } } @Override public String toString() { return "Book [author=" + author + ", name=" + name + ", ISBN=" + ISBN + ", language=" + language + ", weight=" + weight + "]"; } }
使用方式:ui
Book book = new Book.Builder("author", "name", "ISBN") .language("language") .weight(2) .build();
實現方式2:this
public class Book { private final String author; //必須 private final String name; //必須 private final String ISBN; //必須 private final String language; //非必須 private final int weight; //非必須 private Book(Builder builder){ author = builder.author; name = builder.name; ISBN = builder.ISBN; language = builder.language; weight = builder.weight; } public static Builder builder(String author,String name,String ISBN){ return new Builder(author,name,ISBN); } private static class Builder{ private final String author; private final String name; private final String ISBN; private String language; private int weight; public Builder(String author, String name, String iSBN) { this.author = author; this.name = name; ISBN = iSBN; } public Builder language(String language){ this.language = language; return this; } public Builder weight(int weight){ this.weight = weight; return this; } public Book build(){ return new Book(this); } } @Override public String toString() { return "Book [author=" + author + ", name=" + name + ", ISBN=" + ISBN + ", language=" + language + ", weight=" + weight + "]"; } }
使用方式:spa
Book book = Book.builder("author", "name", "ISBN") .language("language") .weight(2) .build();