1 / 114

Chapter 13 Flyweight

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.

liko
Download Presentation

Chapter 13 Flyweight

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 13Flyweight Summary prepared by Kirk Scott

  2. Design Patterns in JavaChapter 13Flyweight Summary prepared by Kirk Scott

  3. 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…

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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

  9. 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

  10. 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

  11. 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

  12. 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)

  13. 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

  14. 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

  15. 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?

  16. 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

  17. 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.”

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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

  24. 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

  25. 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

  26. 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

  27. 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

  28. 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

  29. 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.

  30. 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

  31. 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

  32. 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

  33. 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

  34. 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”

  35. 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

  36. 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

  37. 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

  38. 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

  39. 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

  40. 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.”

  41. 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.]

  42. public double getAtomicWeight() • { • return chemical.getAtomicWeight(); • } • public double getGrams() • { • return grams; • } • public double getMoles() • { • return grams / getAtomicWeight(); • }

  43. 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

  44. Substance2 provides an interface to the chemicals to the client • The Substance2 interface is implemented by delegation, calling methods on the wrapped chemical object

  45. 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

More Related