在 Java 中,不可变类(Immutable Class)指对象一旦创建,其状态(字段值)就不能再被修改。设计不可变类是并发安全和代码可维护性的重要手段。
下面从设计原则、示例、常见注意点、JDK 示例几个方面说明。
private finalfinal 修饰public final class ImmutableClass
finalprivate final int value;
public final class User {
private final String name;
private final int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
✅ 特点:
finalfinalpublic final class User {
private final Date birthDate;
public User(Date birthDate) {
this.birthDate = birthDate;
}
public Date getBirthDate() {
return birthDate; // ⚠️ 外部可修改
}
}
User user = new User(new Date());
user.getBirthDate().setTime(0); // 修改内部状态
import java.util.Date;
public final class User {
private final Date birthDate;
public User(Date birthDate) {
this.birthDate = new Date(birthDate.getTime());
}
public Date getBirthDate() {
return new Date(birthDate.getTime());
}
}
import java.util.List;
import java.util.Collections;
public final class Group {
private final List<String> members;
public Group(List<String> members) {
this.members = Collections.unmodifiableList(
new ArrayList<>(members)
);
}
public List<String> getMembers() {
return members;
}
}
import java.util.List;
public final class Group {
private final List<String> members;
public Group(List<String> members) {
this.members = List.copyOf(members);
}
public List<String> getMembers() {
return members;
}
}
当字段较多时,构造参数过多会影响可读性。
public final class Person {
private final String name;
private final int age;
private final String address;
private Person(Builder builder) {
this.name = builder.name;
this.age = builder.age;
this.address = builder.address;
}
public static class Builder {
private String name;
private int age;
private String address;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Builder address(String address) {
this.address = address;
return this;
}
public Person build() {
return new Person(this);
}
}
}
使用:
Person p = new Person.Builder()
.name("Tom")
.age(20)
.address("Beijing")
.build();
✅ 线程安全
✅ 缓存友好
✅ 易于推理
✅ 适合作为 Map 的 key
String、Integer 都是不可变类| 类 | 说明 |
|---|---|
String |
字符串不可变 |
Integer |
包装类 |
BigDecimal |
数值计算 |
LocalDate |
时间 API |
List.of() |
不可变集合 |
不可变类 = final 类 + final 字段 + 无 setter + 防御性拷贝 + 不暴露可变引用
如果你愿意,我也可以帮你:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。