什么是不可变对象(immutable object)?Java 中怎么创建一个不可变对象?

一、概念

不可变对象指对象一旦被创建,状态就不能再改变。任何修改都会创建一个新的对象,如 String、Integer及其它包装类。详情参见答案,一步一步指导你在 Java 中创建一个不可变的类。


二、创建不可变类的规则如下:

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.


三、例:
public final class Contacts {

	private final String name;
	private final String mobile;
	
	public Contacts(String name, String mobile) {
		this.name = name;
		this.mobile = mobile;
	}

	public String getName() {
		return name;
	}

	public String getMobile() {
		return mobile;
	}
}

public final class ImmutableReminder {

	private final Date remindingDate;
	
	public ImmutableReminder(Date remindingDate) {
		if (remindingDate.getTime() < System.currentTimeMillis()) {
			throw new IllegalArgumentException("Can not set reminder for past time: " + remindingDate);
		}
		this.remindingDate = new Date(remindingDate.getTime());
	}

	public Date getRemindingDate() {
		return (Date) remindingDate.clone();
	}
}

猜你喜欢

转载自blog.csdn.net/aishangyutian12/article/details/53611338