java之不可变对象2(immutable objects in java)
Immutable objects are simply objects whose state (the object's data) cannot change after construction.
Examples of immutable objects from the JDK include String and Integer.
Immutable objects greatly simplify your program, since they :
are simple to construct, test, and useare automatically thread-safe and have no synchronizationissuesdo not need a copy constructordo not need an implementation of cloneallow hashCode to use lazy initialization, and to cache its return valuedo not need to be copied defensively when usedas a fieldmake good Map keys and Set elements (these objects mustnot change state while in the collection)have their class invariant established once upon construction,and it never needs to be checked againalways 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?
?
?
?
Note that javadoc1.4 includes the -tag option, whereby simple custom tags maybe defined. One might define an @is.Immutable tag, for example,to document a class as being immutable.You might also consider defining your own tag interface for immutable objects.
?
?
?
?
?