不可变类 Immutable class 之 偷知识,偷到即是赚到

什么是不可变类?
这个class里的变量被初始化后不能被改变
A class who’s instance cannot be changed after it’s been initialized.

不可变类介绍:
– The state of each instance of an immutable is fixed at
instantiation
– java.lang.String is an immutable class
– java.util.Date is not immutable (but should be!)

To make a class immutable
– Do not provide mutator methods that modify object state(可以理解为不能有set 方法)
– Forbid method overriding(不能有 overriding 的方法)
– Make all fields private and final
– Use defensive copying to guarantee exclusive access to any immutable components

这里有一个 不可变类“ImmutablePerson”。。但其实这个不能算是正确的不可变类

public final class ImmutablePerson {
	private final Name name;
	private final Date dateOfBirth;
	public ImmutablePerson(Name name, Date dateOfBirth)
	{
	if (name == null)
		throw new IllegalArgumentException(…);
	if (dateOfBirth == null)
		throw new IllegalArgumentException(…);
		this.name = name;
		this.dateOfBirth = dateOfBirth;
	}
	public Name getName() { return name; }
	public Date getDateOfBirth() { return dateOfBirth; }
}

附带name类

public final class Name {
	private String firstName;
	private String lastName;
	// constructor goes here
	public String getFirstName() { return firstName; }
	public String getLastName() { return lastName; }
	public void setFirstName(String firstName) {
		// check parameter here
		this.firstName = firstName;
	}
	public void setLastName(String lastName) {
		// check parameter here
		this.lastName = lastName;
	}
}

那真确的应该是这样哒

public final class ImmutablePerson {
	private final Name name;
	private final Date dateOfBirth;
	public ImmutablePerson(Name name, Date dateOfBirth) {
	// throw NullPointerException for null parameters
		this.name = new Name(name.getFirstName(),
		name.getLastName());
		this.dateOfBirth = new Date(dateOfBirth.getTime());
	}
	public Name getName() {
		return new Name(name.getFirstName(),name.getLastName());
	}
	public Date getDateOfBirth() {
		return (Date) dateOfBirth.clone();
	}
}

不可变类有啥优点呢?
• Immutables are simple and safe and make good building blocks
• An immutable is only ever in exactly one state
• Immutables are thread-safe
• Immutables can be catched
• There is no need to defensively copy or clone an immutable
• Mutable classes built on a foundation of immutable components are easier to maintain
• Safe as set elements or map keys
• So: minimize mutability

总结一下:不可变类就是防止数据被更改,不可变类里会运用到了 防御式编程(defensive programming) 中的 防御式复制 (defensive copying),也就是 get方法返回一个对象的时候,(假设这个对象是Q1), 直接返回一个新建的对象(假设这个对象是Q2),让Q1 和 Q2 的值 相同 但是hashcode不一样(储存的地址不一样)。这样可以让 之后针对这个Q2 的改动 不会影响到Q1,就是这样,汪。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值