标签:
Builder模式适用于构造对象时,需要多个参数的情况。对于多个参数,用方法名也能很好的说明用途。
但为了构造对象,就必须先创建它的Builder构建器,在某些十分注重性能的情况下,就可能是一个性能问题。
实现方式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 null; } } @Override public String toString() { return "Book [author=" + author + ", name=" + name + ", ISBN=" + ISBN + ", language=" + language + ", weight=" + weight + "]"; } }
使用方式:
Book book = new Book.Builder("author", "name", "ISBN") .language("language") .weight(2) .build();
实现方式2:
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 null; } } @Override public String toString() { return "Book [author=" + author + ", name=" + name + ", ISBN=" + ISBN + ", language=" + language + ", weight=" + weight + "]"; } }
使用方式:
Book book = Book.builder("author", "name", "ISBN") .language("language") .weight(2) .build();
标签:
原文地址:http://my.oschina.net/u/1756290/blog/379509