黑马程序员技术交流社区
标题:
分享一个用Java实现建造者模式的代码
[打印本页]
作者:
shaoshuai
时间:
2015-2-5 11:32
标题:
分享一个用Java实现建造者模式的代码
本帖最后由 shaoshuai 于 2015-2-5 11:33 编辑
话不多少,直接上代码:
public class User {
private long id;
private String username;
private String password;
private String email;
private String address;
public User(){
}
public User(UserBuilder builder) {
this.id = builder.id;
this.username = builder.username;
this.password = builder.password;
this.email = builder.email;
this.address = builder.address;
}
public long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public String getAddress() {
return address;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
return true;
}
static class UserBuilder {
private long id;
private String username;
private String password;
private String email;
private String address;
public UserBuilder(long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public UserBuilder email(String email) {
this.email = email;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2