直接上代码
public class Contact {
final String name;
final String email;
final String phone;
private Contact(final Builder builder){
this.name = builder.name;
this.email = builder.email;
this.phone = builder.phone;
}
public String toString(){
String str = "name = "+this.name+", email = "+this.email+", phone = "+this.phone;
System.out.println(str);
return str;
}
public static class Builder{
private String name;
private String email;
private String phone;
public Builder(){
}
public Builder setName(String name){
this.name = name;
return this;
}
public Builder setEmail(String email){
this.email = email;
return this;
}
public Builder setPhone(String phone){
this.phone = phone;
return this;
}
public Contact build(){
if(this.name == null){
this.name = "Andy";
}
if(this.email == null){
this.email = "xxxxxxx@163.com";
}
if(this.phone == null){
this.phone = "xxxxxxxxxxx";
}
return new Contact(this);
}
}
}
测试调用
Contact contact = new Contact.Builder().build();
contact.toString();
Contact contact1 = new Contact.Builder().setName("andy").setEmail("andy@163.com").setPhone("11111111111").build();
contact1.toString();
name = Andy, email = xxxxxxx@163.com, phone = xxxxxxxxxxx
name = andy, email = andy@163.com, phone = 11111111111
**如有错误请博友指出!**