用java写一个建造者模式代码
时间: 2023-05-22 16:07:01 浏览: 99
java 建造者模式代码
好的,下面是一个用 Java 实现建造者模式的示例代码:
```
public class User {
private final String firstName; // 必填项
private final String lastName; // 必填项
private final int age; // 可选项
private final String phone; // 可选项
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
}
// 省略getter方法
// 建造者类
public static class UserBuilder {
private final String firstName; // 必填项
private final String lastName; // 必填项
private int age; // 可选项
private String phone; // 可选项
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public User build() {
return new User(this);
}
}
}
// 调用示例
User user = new User.UserBuilder("San", "Zhang")
.age(18)
.phone("139xxxxxx")
.build();
```
以上代码实现了一个包含必填项和可选项的实体类 `User` 和与之对应的建造者类 `UserBuilder`。在构建实体对象时,先使用建造者类设置必填项和可选项的值,最后调用 `build()` 方法构建实体对象。
阅读全文