1、Java Builder模式主要是用一个内部类去实例化一个对象,避免一个类出现过多构造函数,而且构造函数如果出现默认参数的话,很容易出错。
public Person(String name)
Person(String name, int age)
Person(String name, int age, boolean sex)
2、Android OkHttp框架中Request、Response类都使用了Java Builder模式。
3、下面举一个小例子:
/** * @author SunKing1927 2015年11月2日 * Java Builder模式 */ public class Person { private String name; private int age; private boolean sex; public String getName() { return name; } public int getAge() { return age; } public boolean isSex() { return sex; } public static class Builder { private String name; private int age; private boolean sex; public Builder name(String n) { name = n; return this; } public Builder age(int a) { age = a; return this; } public Builder sex(boolean s) { sex = s; return this; } public Person build() { return new Person(this); } } private Person(Builder builder) { name = builder.name; age = builder.age; sex = builder.sex; } }
public class MainRun { public static void main(String[] argv){ Person person = new Person.Builder().name("StephenHe").age(20).sex(true).build(); System.out.println(person.getName() + " " + person.getAge() + " " + person.isSex()); } }
4、参考博文:
http://www.cnblogs.com/moonz-wu/archive/2011/01/11/1932473.html