在 Java 中,不可变对象(Immutable Object)是指创建后状态不能被修改的对象。设计不可变对象有一套成熟且推荐的做法,下面系统地讲一下。
final 修饰(防止被继承)public final class User {
}
防止子类重写行为破坏不可变性。
private final 修饰private final String name;
private final int age;
private:外部不能直接访问final:引用或值不能重新赋值// 没有 setName / setAge
public User(String name, int age) {
this.name = name;
this.age = age;
}
⚠️ 重点易错点
如果字段是可变对象(如 Date、List、数组):
public final class Order {
private final List<String> items;
public Order(List<String> items) {
this.items = new ArrayList<>(items); // 防御性拷贝
}
public List<String> getItems() {
return new ArrayList<>(items); // 返回拷贝
}
}
否则外部仍可通过引用修改内部状态。
String、Integer 等)可以直接返回public final class Person {
private final String name;
private final int age;
private final List<String> hobbies;
public Person(String name, int age, List<String> hobbies) {
this.name = name;
this.age = age;
this.hobbies = new ArrayList<>(hobbies);
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<String> getHobbies() {
return new ArrayList<>(hobbies);
}
}
✅ 创建后无法修改
✅ 线程安全
✅ 可安全共享
HashMap 的 keyStringInteger、Long、BigDecimalLocalDate / LocalDateTimeOptionalpublic final class User {
private final String name;
private final int age;
private User(Builder b) {
this.name = b.name;
this.age = b.age;
}
public static class Builder {
private String name;
private int age;
public Builder name(String name) { this.name = name; return this; }
public Builder age(int age) { this.age = age; return this; }
public User build() {
return new User(this);
}
}
}
使用:
User u = new User.Builder()
.name("Tom")
.age(18)
.build();
如果你愿意,我也可以:
你更想了解哪一块?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。