Guajara in other languages: Spanish, Deutsch, French, Italian ...



Immutable pattern

The Immutable pattern means the data within an Object can not be changed. This is the opposite of a Mutable Object where the data it contains can be changed. Most Objects are Mutable. When an immutable object is instantiated the data that it represents will not be changed under any circumstances. A perfect example is the Java String Object.

String abc = “ABC”;
abc.toLower( );

The method toLower( ) will have no impact on the data abc contains, "ABC”. What will happened is a new String Object will be instantiated and given the data “abc” during its construction. The returned String Object will always refer to the string “abc”. So to make the String Identifier abc contain the data “abc” we need to do the following:

abc = abc.toLower( );

Now the Identifier abc references a new String Object that contains “abc”.

You will notice that the String Object’s method will never affect the data the String Object contains, excluding the constructor. In Java you can enforce this policy by defining the data final during construction.

This pattern is typically must useful in multi-thread applications. This is because when an operation is be executed against a piece of data that an Immutable Object represents then another thread can act on that same data without fear of the data changing during its operation.

Other Immutable Classes to consider: Date, Byte, Character, Short, Integer, Long, Float and Double

Similar patterns are Immutable Interface and the Immutable Wrapper.





Wikipedia - All text is available under the terms of the GNU Free Documentation License.

Tagoror dot com  -  Legal Information  -  Contact us