如何使一个java类不可变

1.不可变的类有什么好处

  1. are simple to construct, test, and use
  2. are automatically thread-safe and have no synchronization issues
  3. do not need a copy constructor
  4. do not need an implementation of clone
  5. allow hashCode to use lazy initialization, and to cache its return value
  6. do not need to be copied defensively when used as a field
  7. make good Map keys and Set elements (these objects must not change state while in the collection)
  8. have their class invariant established once upon construction, and it never needs to be checked again
  9. 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

二、如何使一个类不可变

Java documentation itself has some guidelines identified in this link. We will understand what they mean actually:

1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.

This principle says that for all mutable properties in your class, do not provide setter methods. Setter methods are meant to change the state of object and this is what we want to prevent here.

2) Make all fields final and private

This is another way to increase immutability. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.

3) Don’t allow subclasses to override methods

The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.

4) Special attention when having mutable instance variables


引用自:https://howtodoinjava.com/core-java/basics/how-to-make-a-java-class-immutable/


猜你喜欢

转载自blog.csdn.net/leftmumu/article/details/79984403