620 likes | 758 Views
Unit 12 Flyweight. Summary prepared by Kirk Scott. Design Patterns in Java Chapter 13 Flyweight. Summary prepared by Kirk Scott. The book states that most typically just one object will hold a single reference to another object
E N D
Unit 12Flyweight Summary prepared by Kirk Scott
Design Patterns in JavaChapter 13Flyweight Summary prepared by Kirk Scott
The book states that most typically just one object will hold a single reference to another object • As a result, 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 • There is no need to inform any other objects
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 will want to share access to the object • This is a responsibility pattern because now many references/many clients are potentially responsible for making changes to the object • This is shared responsibility • Also, potentially many client reference/many clients have to be informed of a change
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 are the flyweights • They are shared among different books and each book will have multiple references to them • What characteristics the flyweights have and how to manage them are at the heart of the design 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: • I believe that it would be preferable to say “large numbers of references to fine-grained objects”, although there may also be a large number of objects
Immutability • Part of the introductory discussion mentioned the idea that if a shared object is changed, then potentially all clients should be notified • Stated another way, a single action by one client can potentially affect many other clients • This kind of dependence among the clients can be an undesirable kind of coupling • Also, trying to notify many clients of changes can be onerous
Although it may diminish the usefulness of flyweights in certain applications, the problem can be solved by making the flyweights immutable • This means that their implementation contains no method that allows them to be changed by a client • References to them 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
Challenge 13.1 • Provide a justification of why the creators of Java made String objects immutable, or argue that this was an unwise restriction.
An argument for the immutability of strings: • In short, this is the book’s answer: • Strings are frequently shared • In other words, they are sort of like system supplied flyweights • Therefore, to solve the flyweight problem, it was a good thing to make them immutable
Comment mode on: • The book also touches on this argument, but not very clearly • When you have objects with String instance variables, how should you write the get methods for them? • In reality, you should return a clone • It violates encapsulation to return a reference • However, this problem is solved if the reference returned is immutable
An argument against the immutability of strings: • In short, this is 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
Extracting the Immutable Part of a Flyweight • The starting point for this discussion is that we’re going to assume that if we use the Flyweight design pattern, the flyweights are going to be immutable • The previous discussion explained why that is a desirable design choice • The point of this section is that you have a design with lots of shared references which are not flyweights • You want to refactor to a design that uses flyweights
Along with any other changes to the code, this will require redesigning the class with many references to it as a(n immutable) flyweight • The goal is to extract out the immutable part of the class • That will be the flyweight which has many references to it • The rest of the class will have to be handled in a different way
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
In any case, some of the instance variables identify and give characteristics of chemical elements and compounds • 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) • In other words, grams are a measurement of a quantity of something
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 • The “what it is” part could be immutable • The “how much of it is there” part would be mutable
The Substance class has get and set methods for its instance variables • 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 • 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 or represented • This means that there would be many references to instances of the Substance class • The instances of the substance class would differ according to the number of grams • The information about a particular chemical element or compound would not differ
Challenge 13.2 • Complete the class diagram in Figure 13.3 to show a refactored Substance2 class and a new, immutable Chemical class.
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(); • }
Sharing Flyweights • Extracting the immutable part of a class in order to create flyweights is just part of the task involved in applying the Flyweight pattern • The book refers to creating a “flyweight factory” • This is a foreshadowing of future chapters
The underlying idea is that there should be only one instance of a flyweight containing a certain set of values • If this is the case, then applications can’t just create instances of the flyweight class willy-nilly • The flyweight factory class controls the creation of flyweights and making them available for sharing by clients
For the chemical example the book proposes a ChemicalFactory class • It will contain a static method that will return a reference to a chemical given its name • Internally the factory class can store the different chemicals in a hash table, for example
Notice two things about this scenario • First • The flyweight isn’t a singleton—there are multiple instances of it • However, there can be no duplicate instances • In other words, no two instances of a flyweight should test equal for contents
Second • There is an implementation similarity between the flyweight and the mediator • Recall that one of the example of the use of the Mediator design pattern was maintaining relational integrity • This was accomplished in part by wrapping a hash table in a class and then storing individual items as entities in the hash table
Not only is the similarity structural • In a real sense the flyweight factory is a specific example of the mediator pattern • It maintains the list of chemicals • It is responsible for making the chemicals available for sharing by client code • The UML diagram on the next overhead illustrates the relationships between the ChemicalFactory class and the Chemical class
Next the book shows code for the ChemicalFactory class • The book makes use of what it calls a static initializer • Basically this can be summarized as a block of code that is used to initialize an instance variable • In this example there is an instance of HashMap and it is filled with instances of the chemical class
It would be possible to put the static initialization code into a constructor for a class that had instances • Since the one method of interest in the ChemicalFactory class is static, its methods are not called on an instance
Another side note is this: An alternative to a class containing only static items would be a singleton class • You would have to create the one instance of the singleton and then call real methods on that instance • Partial code for the ChemicalFactory class is shown on the following overheads
import java.util.*; • public class ChemicalFactory • { • private static Map chemicals = new HashMap(); • static • { • chemicals.put("carbon", new Chemical("Carbon", "C", 12)); • chemicals.put("sulfur", new Chemical("Sulfur", "S", 32)); • chemicals.put("saltpeter", new Chemical("Saltpeter", "KN03", 101)); • //... • } • public static Chemical getChemical(String name) • { • return (Chemical) chemicals.get(name.toLowerCase()); • } • }
Developers should not create their instances of the chemical class • They should only use the chemicals in the ChemicalFactory class • Enforcing this discipline can be accomplished by controlling access to the Chemical class
Challenge 13.3 • How can you use the accessibility of the Chemical class to discourage other developers from instantiating Chemical objects?
Solution 13.3 • 1. One way that won’t work is to make the Chemical constructor private. • That would prevent the ChemicalFactory class from instantiating the Chemical class • Comment mode on: • This is not a solution
2. To help prevent developers from instantiating the Chemical class themselves, you could place Chemical and ChemicalFactory classes in the same package and give the Chemical class’s constructor default (“package”) access. • Comment mode on: • To be charitable, this is a weak solution. • Lame might be a better word
You can prevent client code from creating instances of the Chemical class by making it an inner class of the ChemicalFactory class • Note that client code would have to use the qualified class name when referring to an instance of the inner class • You are familiar with this notation • An example is shown on the next overhead
ChemicalFactory.Chemical c = ChemicalFactory.getChemical(“saltpeter”);
The book suggests a refinement on this plan • Let the inner class be named ChemicalImpl, short for ChemicalImplementation • Let there be an interface named Chemical • Let the inner class implement the interface • Then internal to the factory, instances of ChemicalImpl are created
The getChemical() method of the factory is defined to return a reference of type Chemical • Client code works with references of type Chemical • In this way, the client never has to refer to the actual ChemicalImpl class • The client never has to use a qualified name