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 / 101

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. Under the principle that responsibility is localized, when programming, typically just one object will hold a single reference to another object

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. Under the principle that responsibility is localized, when programming, typically just one object will hold a single reference to another object • 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

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

    5. Many references/many clients are potentially responsible for making changes to the object • Many client reference/many clients may have to be informed of a change • This is a pattern involving shared responsibility

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

    7. In this scenario it is the individual character objects that are the flyweights • What characteristics the flyweights have and how to manage them are at the heart of the design pattern

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

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

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

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

    12. Challenge 13.1 • Provide a justification of why the creators of Java made String objects immutable, or argue that this was an unwise restriction.

    13. An argument for the immutability of strings: • In short, this is 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

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

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

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

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

    18. Extracting the Immutable Part of a Flyweight • With multiple references, it can be useful for a shared object to be immutable • The assumption now will be that flyweights should be immutable • This section starts with a design with lots of shared references which are not flyweights • You want to refactor to a design that uses flyweights

    19. The primary goal is to extract out the immutable part of the flyweight class • That class will be redesigned • Other parts of the class will have to be handled in a different way • The application that uses the class will also need to be changed

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

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

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

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

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

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

    26. The UML diagram only showed get methods, but in general, 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

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

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

    29. Challenge 13.2 • Complete the class diagram in Figure 13.3 to show a refactored Substance2 class and a new, immutable Chemical class.

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

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

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

    33. Flyweight and Object Adapter • At this stage of development you observe that the flyweight pattern has similarities with the object adapter design pattern. • The new Substance class provides an interface to a chemical compound, as well as additional characteristics (mass) needed by the client • It does so by wrapping a reference to a chemical (a compound) and directly delegating some method calls to that object

    34. 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 patterns that will be covered later (Factory Method, Abstract Factory)

    35. The idea is that there should be only one instance of a flyweight containing a certain set of values • Applications can’t just create instances of the flyweight class willy-nilly • The flyweight factory class controls the creation of flyweights and makes them available for sharing by clients

    36. 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 the chemical’s name • Internally the factory class will store the different chemicals in a hash table

    37. You may recall that the book’s example of the mediator involved the use of a hash table • After a fuller discussion of flyweight, its relationship with other patterns will be considered at greater length

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

    39. Next the book shows code for the ChemicalFactory class • There is no need to construct an instance of the class, and it doesn’t have a constructor • The class contains a static HashMap which holds instances of chemicals • The HashMap is created using inline construction where it is declared in ChemicalFactory

    40. The book makes use of what it calls a static initializer for the HashMap • This is a block of code that follows the inline construction of the HashMap and constructs instances of chemicals, putting them into the HashMap • Because the initializer is declared static, it is run once, when the class is loaded.

    41. The overall purpose of the class is to make chemicals available. • The class contains a static method to retrieve references to chemicals (from the hash table) and return them to callers • As a static method, it is called like methods in the Math class

    42. This is tangential to the flyweight pattern, but it further illuminates the singleton pattern: • A singleton class would be an alternative to a class containing only static methods • The static initialization code could be put into the constructor for the singleton • Instead of calling static methods, you would create the one instance of the singleton and call non-static methods on that instance

    43. Partial code for the ChemicalFactory class is shown on the following overheads

    44. 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()); • } • }