Sharing Flyweights

Extracting the immutable part of an object is half the battle in applying the FLYWEIGHT pattern. The remaining work includes creating a flyweight factory that instantiates flyweights and that arranges for clients to share them. You also have to ensure that clients will use your factory instead of constructing instances of the flyweight class themselves.

To make chemicals flyweights, you need a factory, perhaps a ChemicalFactory_1 class, with a static method that returns a chemical given its name. You might store chemicals in a hash map, creating known chemicals as part of the factory's initialization. Figure 13.4 shows a design for a ChemicalFactory_1. The code for ChemicalFactory_1 can use a static initializer to store Chemical_1 ...

Get Design Patterns Java™ Workbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.