当一个类的变量比较多,构造函数也比较多,用重载构造函数的方法,会导致有客户端代码比较难维护,用这种Builder构造器来实现,扩展性好,便于维护。
/**
* Created by wzj on 2016/9/11.
*/
public class BuilderMode
{
private int id;
private String name;
private String age;
private String score;
public static class Builder
{
//初始化
private final int id;
private String name = "";
private String age = "";
private String score = "";
//id是不能够改变的
public Builder(final int id)
{
this.id = id;
}
public Builder name(final String name)
{
this.name = name;
return this;
}
public Builder age(final String age)
{
this.age = age;
return this;
}
public Builder score(final String score)
{
this.score = score;
return this;
}
public BuilderMode build()
{
return new BuilderMode(this);
}
}
//构造函数
public BuilderMode(Builder builder)
{
this.id = builder.id;
this.name = builder.name;
this.age = builder.age;
this.score = builder.score;
}
@Override
public String toString()
{
return id + "--" + name + "--" + age + "--" + score;
}
public static void main(String[] args)
{
//构建对象
BuilderMode.Builder builder = new BuilderMode.Builder(1001);
BuilderMode builderMode = builder.name("wzj").age("23").score("100").build();
System.out.println(builderMode.toString());
}
}