Java Reference
In-Depth Information
Flyweight (Chapter 13)
SOLUTION 13.1
The BorderFactory class in javax.swing is a good example of F LYWEIGHT . As its
class comment says, "Wherever possible, this factory will hand out references to shared
Border instances." When a Border object can be safely shared, BorderFactory will
return the same border more than once. For example, every call to createEmptyBorder()
will return the same, empty border.
SOLUTION 13.2
An argument for the immutability of strings: In practice, strings are frequently shared
between clients and thus frequently the crux of defects that emerge when one client
inadvertently affects another. For example, a method that returns a customer's name as
a string will typically retain its reference to the name. If the client, say, uppercases the
string to use it in a hash table, the Customer object's name would change as well, if
not for the immutability of strings. In Java, you can produce an uppercase version of a
string, but this must be a new object, not an altered version of the initial string. The
immutability of strings makes them safe to share among multiple clients.
Against: The immutability of strings protects us from certain errors but at a heavy
price. First, developers are cut off from any ability to change a string, regardless of
how we might justify this need. Second, adding special rules to a language makes the
language more difficult to learn and to use. Java is far, far more difficult to learn than
the equally powerful Smalltalk language. Finally, no computer language can keep me
from making errors. I'd be much better off if you let me learn the language quickly, so
that I have time to also learn how to set up and use a testing framework.
SOLUTION 13.3
The name, symbol, and atomic weight of chemicals do not change, so you can refactor the
Substance class as Figure B.18 shows. The refactoring moves the immutable, or intrinsic,
aspect of a particular substance into the Chemical class. Note that the Chemical class's
immutability relies on the fact that its attributes cannot change once the Chemical object is
created. The class's immutability also relies on the immutability of its attributes. If
Chemical contained, say, a List object, a chemical could change if its list changed.
Figure B.18. This diagram shows the immutable part of the Substance class extracted
into a separate class, Chemical .
Search WWH ::




Custom Search