多个构造器参数使用构造器代替 取自effective java

本文介绍了一个使用Java实现的Builder模式案例,通过该模式创建Person对象。案例中详细展示了如何定义带有必填和选填参数的构造器,并通过具体示例说明了如何利用Builder模式灵活地构造不同类型的Person实例。
/*************************************************************
 * * 
 *
 * @author seven
 *
 * 2012-10-08 上午10:51:37
 * 
 ***************************************************************/
package effectiveJava;


public class Test{


public static void main(String[] args) {
Person tom = new Person.Builder(1, "tom").build();
Gender andyGender = Gender.MALE;
andyGender.setName("男");
Person andy = new Person.Builder(2, "andy").gender(andyGender)
.address("HongKong").build();
System.out.println(tom.getId());
System.out.println(tom.getName());
System.out.println(andy.getId());
System.out.println(andy.getName());
System.out.println(andy.getGender().getName());
System.out.println(andy.getAddress());
}


}


class Person {
private final int id;
private final String name;
private final Gender gender;
private final String address;
private final String phone;
private final String email;


public static class Builder {
// required parameters
private final int id;
private final String name;


// optional parameters - initialized to default values
private Gender gender = Gender.SECRET;
private String address = null;
private String phone = null;
private String email = null;


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


public Builder gender(Gender gender) {
this.gender = gender;
return this;
}


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


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


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


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


}


private Person(Builder builder) {
id = builder.id;
name = builder.name;
gender = builder.gender;
address = builder.address;
phone = builder.phone;
email = builder.email;
}


public int getId() {
return id;
}


public String getName() {
return name;
}


public Gender getGender() {
return gender;
}


public String getAddress() {
return address;
}


public String getPhone() {
return phone;
}


public String getEmail() {
return email;
}
}


enum Gender {
MALE("male"), FAMALE("famale"), OTHER("other"), SECRET("secret");
private String name;


private Gender() {
};


private Gender(String name) {
this.name = name;
}


public void setName(String name) {
this.name = name;
}


public String getName() {
return this.name;
}
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值