Friday, December 17, 2004 02:05 AM
An object can only be immutable if it does not have any methods that change ("mutate") its state. So you cannot make an object immutable - the writer of the class
must decide whether the class should create immutable objects (like String, Integer, ...) or not (like StringBuffer, customary collections, ...).
If the design is perfect - i.e., the class implements an interface; and all client code is written against the interface, then you can add an "immutable wrapper" via the Decorator pattern by simply implementing
- all non-mutating methods with a call to a mutable delegate;
- throwing an UnsupportedOperationException on all mutating methods.
See Collections.unmodifiable...() for an example of this design.