1.Topics‎ > ‎Architecture‎ > ‎Patterns‎ > ‎a.Design Patterns‎ > ‎C.Structural Patterns‎ > ‎

I.Fly Weight Pattern

  1. Summary 
    1. Allow sharing to object to conserve system resources when a large number of objects need to be created.
    2. This is usually achieved by sharing significant portion of object state and functionality.
  2. Overview Tutorials
    1. http://sourcemaking.com/design_patterns/flyweight
    2. http://www.oodesign.com/flyweight-pattern.html
  3. Example
    1. Games with graphics as discussed with the War Game Example
    2. Text Editors as discussed in the Text Editors example.
  4. Implementation (algorithm)
    1.  A client needs a flyweight object; it calls the factory to get the flyweight object.
    2.  The factory checks a pool of flyweights to determine if a flyweight object of the requested type is in the pool, if there is, the reference to that object is returned.
    3.  If there is no object of the required type, the factory creates a flyweight of the requested type, adds it to the pool, and returns a reference to the flyweight.
    4.  The flyweight maintains intrinsic state (state that is shared among the large number of objects that we have created the flyweight for) and provides methods to manipulate external state (State that vary from object to object and is not common among the objects we have created the flyweight for).
  5. Specific Considerations
    1. Flyweight VS Factory and Singleton patterns
      1. Flyweights are usually created using a factory and the singleton is applied to that factory so that for each type or category of flyweights a single instance is returned.
    2. Flyweight VS State and Strategy Patterns
      1. State and Strategy objects are usually implemented as Flyweights.
    3. Resourcing Saving
      1. Flyweight pattern saves memory by sharing flyweight objects among clients.
      2. The amount of memory saved generally depends on the number of flyweight categories saved (for example a soldier category and a lieutenant category as discussed earlier).