Java建造者模式代码示例
时间: 2024-02-23 08:27:06 浏览: 70
好的,以下是Java建造者模式的代码示例:
```
public class User {
private String username;
private String password;
private int age;
private String address;
private User(UserBuilder builder) {
this.username = builder.username;
this.password = builder.password;
this.age = builder.age;
this.address = builder.address;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
public static class UserBuilder {
private String username;
private String password;
private int age;
private String address;
public UserBuilder(String username, String password) {
this.username = username;
this.password = password;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
```
使用建造者模式创建 User 对象的示例代码如下:
```
User user = new User.UserBuilder("username", "password")
.age(20)
.address("123, Main Street")
.build();
```
这样我们就可以使用链式调用来创建 User 对象,比直接在构造函数中传入参数更加灵活和易用。
阅读全文