Java Reference
In-Depth Information
Chapter 13. Flyweight
The flyweight pattern addresses sharing, relying on an object's ability to be responsible to
more than a single client. An ordinary object doesn't have to worry much about shared
responsibility. Often, only one client will hold a reference to an object at any one time. When
the object's state changes, it's because the client changed it, and the object does not have any
responsibility to inform any other clients. Sometimes, though, you will want to arrange for
multiple clients to share access to an object.
One incentive for sharing an object among multiple clients occurs when you must manage
thousands or tens of thousands of small objects, such as the characters in an online version of
a topic. In such a case, you may have a performance incentive to share these fine-grained
objects among many clients. A book needs only one A object, although it needs a way to
model where different A s appear.
In any application having a large number of small objects, you may need to provide a way for
clients to safely share the common elements of these objects. The intent of the F LYWEIGHT
pattern is to use sharing to support large numbers of fine-grained objects efficiently.
Recognizing Flyweight
To provide for the sharing of flyweight objects, you need a class with a method other than a
constructor that returns the object to be shared. This lets you control flyweight creation,
ensuring that only one instance of any particular flyweight exists. There is an example of a
flyweight factory in a Swing class that is a factory for Swing components. This class
comment says, "wherever possible, this factory will hand out references to shared ...
instances." We used this class in Chapter 4, Facade, and in Chapter 9, Observer.
CHALLENGE 13.1
Name a Swing class that provides an example of F LYWEIGHT .
Immutability
When a client changes the state of an object, the state changes for every client that has access
to the object. This is no problem when there is only a single client, which is the most ordinary
case. When multiple clients will share access to an object, the easiest and most common way
to keep clients from affecting one another is to restrict clients from introducing any state
changes in the shared object. You can achieve this by making an object immutable so that
once created, the object cannot change. The most common immutable objects in Java are
instances of the String class. Once you create a string, neither you nor any client with
access to the string can change its characters.
Search WWH ::




Custom Search