不可变类(immutable class)

*What is immutable class?
意思是创建一个类后,该类中的实例是不可改变的。例如,java提供的8个包装类就是不可变的,一旦有了初始值后,就不能变了。
示例:
Double d = new Double (6.5);
用了上述代码后,后续Double类并没有提供一个方法能让你修改d的值。


*Why we use the immutable class?
1. 更加简单地去构造、测试以及使用;
2. 自动就能实现“线程安全”,不会有同步问题;
3. 不需要一个“拷贝构造器”(copy constructor);
4. 不需要对“clone”进行实现(implementation);这个什么意思,不懂?
5. 可以让“hashCode”去使用“lazy initialization”,以及去缓存它的返回值;
6. 其他看不懂的原因:
★do not need to be copied defensively when used as a field
make good Map keys and Set elements (these objects must not change state while in the collection)
★have their class invariant established once upon construction, and it never needs to be checked again
★always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state
7. 还可以将常用的实例进行缓存,从而减少对象的创建。


*How to use the immutable class?
1. 使用private以及final修饰符来修饰该类的Field;
2. 提供带参数的构造器,用于根据传入参数来初始化类里的Field;
3. 仅提供getter方法,不提供setter方法;
4. (可选)如有必须,重写Object类的hashCode和equals方法。
示例:
public class Address {
	//1. 使用private以及final关键词修改该类的Field
	private final String detail;
	private final String postCode;


	//2. 使用带参数的构造器,这里提供两个
	public Address () {
		this.detail = "";
		this.postCode = "";
	}
	public Address (String detail, String postCode) {
		this.detail = detail;
		this.postCode = postCode;
	}
	
	//3. 提供getter方法
	public String getDetail () {
		return this.detail;
	}
	public String getPostCode () {
		return  this.postCode;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值