unit 12 flyweight n.
Skip this Video
Loading SlideShow in 5 Seconds..
Unit 12 Flyweight PowerPoint Presentation
Download Presentation
Unit 12 Flyweight

Loading in 2 Seconds...

play fullscreen
1 / 107

Unit 12 Flyweight - PowerPoint PPT Presentation

  • Uploaded on

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

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

Unit 12 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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
    Presentation Transcript
    1. Unit 12Flyweight 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 will 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 • 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 or dependence • Also, trying to notify many clients of changes can be onerous

    12. In general, 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

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

    14. Although immutability is key to the implementation of flyweights, it’s not their only aspect • (If it were, this set of overheads would not drone on at the length they do)

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

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

    17. Comment mode on: • The immutability of strings comes up in CS 202 when discussing encapsulation and cloning • The book also touches on this, but not very clearly • The general rule, as presented in CS 202, is repeated very briefly here

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

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

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

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

    22. 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 the immutability of strings • For the purposes of this design pattern, it is the case that the flyweight class should be immutable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    42. 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 includes creating a “flyweight factory” • This will control the construction of instances

    43. For the the example the book proposes a ChemicalFactory class • It will contain a static method that will return a reference to a chemical given the chemical’s name • Internally the factory class will store the different chemicals in a hash table

    44. You may recall that the book’s example of the mediator involved the use of a hash table • It was used, among other things, to make sure there was only one reference to each tub • It can also be use to make sure there is only one instance of each chemical

    45. The UML diagram on the next overhead illustrates the relationships between the ChemicalFactory class and the Chemical class