您的位置:首页 > 产品设计 > UI/UE

Java (Builder 模式) 解决Contruct构造器中参数过长的问题

2013-03-23 13:55 351 查看
直接上代码,比较容易懂

Builder 模式

public class BeanContruct {

/**
* 必要参数
*/
private final Integer id;

private final String name;

/**
* 可选参数
*/
private final String sex;

private final String age;

private BeanContruct(Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.sex = builder.sex;
this.age = builder.age;
}

public static class Builder {
private Integer id;
private String name;

private String sex;
private String age;

public Builder(Integer id, String name) {
this.id = id;
this.name = name;
}

public Builder sex(String val) {
this.sex = val;
return this;
}

public Builder age(String val) {
this.age = val;
return this;
}

public BeanContruct build() {
return new BeanContruct(this);
}
}

public Integer getId() {
return id;
}

public String getName() {
return name;
}

public String getSex() {
return sex;
}

public String getAge() {
return age;
}

}


测试代码:

@Test
public void test() {
BeanContruct bean = new BeanContruct.Builder(1, "Jack").age("18")
.sex("女").build();
System.out.println(bean.getName());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: