1.15k likes | 1.33k Views
Chapter 13 Flyweight. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 13 Flyweight. Summary prepared by Kirk Scott. That animal is known as a couscous A trip to Wikipedia will allow you to determine whether it is related to the food named couscous…. Introduction.
E N D
Chapter 13Flyweight Summary prepared by Kirk Scott
Design Patterns in JavaChapter 13Flyweight Summary prepared by Kirk Scott
That animal is known as a couscous • A trip to Wikipedia will allow you to determine whether it is related to the food named couscous…
Introduction • Under the principle that responsibility is localized, when programming, typically just one object will hold a single reference to another object • This is related to the idea of cloning • Shallow copies with shared references are not good • In general, any two objects, not necessarily clones of each other, with references to the same object may be problematic
Ideally, just one object holds a reference to another • Any change to the held object will be a result of a call made in the holding object • If this is the case, the holding object knows what’s been done • If no other object holds a reference, no other object needs to be aware of a change
On the other hand, some objects may be referred to by many other objects • Alternatively, a single object may be referred to many times by one other object • Put another way, one or more clients may want to share access to the same object
Many clients/references are potentially capable of making changes to the shared object • Therefore, many clients/references may have to be informed of a change • The flyweight design pattern is intended to effectively manage this shared responsibility for shared objects/references
Initial Scenario • The authors offer this scenario for sharing • Suppose that in a text management system there is a single object for each printable character • Then a book may contain thousands of references to individual instances of the character class • Also, there may be many books overall, each containing multiple references to instances of the character class
In this scenario it is the individual character objects that will be implemented using the flyweight design pattern • What characteristics the flyweights have and how to manage them are at the heart of the pattern
Book Definition of Pattern • Book definition: • The intent of the Flyweight pattern is to use sharing to support large numbers of fine-grained objects efficiently. • Comment mode on: • Not just large numbers of objects, but potentially large numbers of references to those objects
Immutability • Part of the introductory discussion mentioned the idea that if a shared object is changed, then potentially all clients should be notified • They may or may not be notified • The real point is that a single action by one client on an object can potentially affect many other clients with shared references to that object
This kind of dependence among the clients can be an undesirable kind of coupling or dependence • Also, if you want to notify other clients of changes, trying to do that may be onerous • (Although using observability comes to mind as a possible solution)
In general, the problem can be solved by simply making the flyweights immutable • This means that their implementation contains no method that allows them to be changed by a client
References to immutable objects may be dropped • New instances with new values may be created • But an existing object cannot be changed • You are familiar with immutability through the Java String class
At first glance, this may seem like one of those solutions where in order to save the villages it was necessary to destroy the villages • In other words, you eliminate update problems by preventing updating • But what if updating is important?
Although immutability is key to the implementation of flyweights, it’s not their only aspect • The full application of the pattern will include “identifying the immutable part” of something and implementing that part as an immutable flyweight • There will still be room for other characteristics in the design
String Immutability, Good or Bad? • Challenge 13.1 • “Provide a justification of why the creators of Java made String objects immutable, or argue that this was an unwise restriction.”
Good • “An argument for the immutability of strings:” • This is a paraphrase of the book’s answer: • Strings are frequently shared • In other words, the system is supplying a class with this flyweight-like characteristic • Therefore, to solve the difficulties of shared references, it was a good thing to make them into flyweights by making them immutable
Comment mode on: • The immutability of strings comes up in CSCE 202 when discussing encapsulation and cloning • The book also touches on this, but not very clearly • The general rule, as presented in CSCE 202, is repeated very briefly here
When you have objects with instance variables that are references to objects, how should you write the get methods for them? • You should probably return a clone • It violates encapsulation to return a reference • However, this problem is solved if the reference returned is to an immutable object • So the immutability of Strings allows get methods to return references to them without violating encapsulation
Bad • “An argument against the immutability of strings:” • This is a paraphrase of the book’s answer: • By definition, making strings immutable makes it impossible to change them • This is an artificial limitation on strings that doesn’t apply to most other objects
This means Java is less flexible and contains special cases that you have to learn • The authors observe that no language can completely protect the programmer from programming difficulties or making mistakes • If that’s the purpose of immutability, it’s a fool’s errand
The Call of the Wild, Chapter 5 (near the end): • “Thornton went on whittling. It was idle, he knew, to get between a fool and his folly; while two or three fools more or less would not alter the scheme of things.” • The Java API developers struck a balance • By making strings immutable, they supported simple get methods without the concern of cloning
Extracting the Immutable Part of a Flyweight • With multiple references, it can be useful for a shared object to be immutable • Forget the argument about whether it was desirable for strings to be immutable • For the purposes of this design pattern, it is the case that the flyweight class should be immutable • The design pattern requires it and there is no choice
This section starts with a design with lots of shared references to objects which are not flyweights • The problem is that these objects are not immutable • You want to refactor to a design that uses flyweights
The primary goal of refactoring is to extract the immutable part of the class that the shared references are instances of • This immutable part will become a new flyweight class • Other parts of the original class will have to be handled in a different way • These changes in the shared references will also require changes in the application that shares them
Example • The book bases its example on chemicals • In a fireworks factory, the ingredients are chemical in nature • In the non-flyweight design, the ingredients are referred to as substances • The following UML diagram shows the substance class
The Substance class has instance variables for name, symbol, atomicWeight, and grams • A digression on terminology: • The instance variables symbol and atomicWeight suggest that we’re talking about chemical elements • An element has a symbol and an atomic weight
For what it’s worth, the following information is given by Wikipedia: • The IUPAC definition[1] of atomic weight is: • An atomic weight (relative atomic mass) of an element from a specified source is the ratio of the average mass per atom of the element to 1/12 of the mass of an atom of 12C.
It becomes apparent that the authors want to refer to chemical compounds as well as elements • When they refer to a symbol, they don’t just mean a single symbol for an element • They also mean the chemical formula for a compound • Technically, they might also have referred to molecular weight, which is the equivalent for compounds of atomic weight for elements
Distinguishing Mutable from Immutable Attributes • The name, symbol, and atomicWeight instance variables of the Substance class identify and give characteristics of chemical elements and compounds • They tell “what it is” • For any given instance of the Substance class, these attributes would not change • Depending on how the code is structured, they could become attributes of immutable objects
The instance variable gram is different • Grams are a measurement of mass (what we poor benighted users of the English system think of as weight) • It tells “how much there is” • For any given instance of the Substance class, the value of this attribute could vary • Depending on how the code is structured, this could become an attribute of mutable objects
In short, the Substance class tells both what something is and how much of it there is • Such a class invites decomposition into two parts, and logically speaking, this is evident for two reasons: • 1. If you have two kinds of information, that alone may suggest that two classes are desirable
2. The second reason implies the flyweight/immutability argument: • The Substance class is not a singleton • You can have multiple instances of it • If you do, repeating the “what it is” information is redundant • The difference between the instances of the class would only be in the “how much”
Additional Information in the UML Diagram • The UML diagram only showed get methods, but in general, the Substance class would also have set methods • This is why it is mutable • For what it’s worth, it also has a computed getMoles() method that returns the number of moles (6.02 x 1023 molecules, Avogadro’s number of molecules) in a given mass of an element or compound
Instances of the Mixture Class share References to Substance Objects • In the fireworks scenario, there are mixtures of substances as well as substances. • A mixture is a combination of chemicals which are not bound together in a single chemical compound. • The next overhead shows how an instance of the Mixture class is based on having references to instances of the Substance class
In the fireworks setting there could be many different mixtures that have to be modeled • There would be many references to instances of the Substance class • The number of grams could differ among different instances of the substance class
The chemical compound attributes could be the same for multiple instances of the class • Forget about the cosmic difficulties of mutability for a moment • Notice that if there are lots of instance of Substance, there is a lot of redundancy
Refactoring the Design • Challenge 13.2 • “Complete the class diagram in Figure 13.3 to show a refactored Substance2 class and a new, immutable Chemical class.” • Comment mode on: • For a change I’m leaving this as a challenge • It is worth considering the two steps: • Divide the design into two classes • Figure out what goes into each
Solution 13.2 • “You can move the immutable aspects of Substance—including its name, symbol, and atomic weight—into the Chemical class, as Figure B.17 shows.”
Solution 13.2, continued • “The Substance2 class now maintains a reference to a Chemical object. • As a result, the Substance2 class can still offer the same accessors as the earlier Substance class. • Internally, these accessors rely on the Chemical class, as the following Substance2 methods demonstrate.” • [See the next overhead.]
public double getAtomicWeight() • { • return chemical.getAtomicWeight(); • } • public double getGrams() • { • return grams; • } • public double getMoles() • { • return grams / getAtomicWeight(); • }
Flyweight and Object Adapter • You might observe that we saw code very like this in the adapter pattern, for example • Informally, what has been accomplished is this: • Instances of Substance2 “wrap” references to Chemicals
Substance2 provides an interface to the chemicals to the client • The Substance2 interface is implemented by delegation, calling methods on the wrapped chemical object
Sharing Flyweights • Extracting the immutable part of a class in order to create flyweights is one part of applying the Flyweight pattern • Notice that there should only be one instance of the Chemical class for each kind of chemical • Applying the pattern also includes creating a “flyweight factory” • This will control the construction of instances