Java Reference
In-Depth Information
CHALLENGE 13.2
Either justify why the creators of Java made String objects immutable or argue
that this was an unwise restriction.
When you have large numbers of similar objects, you may want to arrange for shared access
to these objects, but they may not be immutable. In this case, a preliminary step in applying
the F LYWEIGHT pattern is to extract the immutable part of an object so that this part can be
shared.
Extracting the Immutable Part of a Flyweight
Around Oozinoz, chemicals are as prevalent as characters in a document. The purchasing,
engineering, manufacturing, and safety departments are all concerned with directing the flow
of thousands of chemicals through the factory. Batches of chemicals are often modeled with
instances of the Substance_1 class, as shown in Figure 13.1.
Figure 13.1. A Substance_1 object models a physical batch of chemical material.
The Substance_1 class has get- methods for its attributes and also has a getMoles()
method that returns the number of moles —a count of molecules—in the substance. For
example, 32 grams of sulfur contains 1 mole of sulfur atoms, as the atomic weight of sulfur is
32. The getMoles() method of the Substance_1 class returns the number of moles that a
particular Substance_1 instance represents.
Search WWH ::




Custom Search