Design Mode (11) FLYWEIGHT)

Source: Internet
Author: User

Problem: If we design a text editor, the object-oriented design method is certainly the first choice. One possible design method is to regard each character, line, and column in the document as an object, which improves Program Flexibility and can be imagined as consuming a large amount of memory. The metadata mode is used to deal with this situation-shared objects, fine-grained processing without high costs.
Intention: Use the sharing technology to effectively support a large number of fine-grained objects.
Motivation: Object-oriented technology greatly improves the efficiency of every link in the software development process, but if you use it too simply, the cost is also great. Take the document editor design mentioned in the introduction as an example. General Design: objects are used to represent each character, line, and column in the Document. Advantages: greatly improving application flexibility. Disadvantage: extremely high memory and running expenses. Release + release/u0 + release/D/release + release/XtMyso6y2 + Mbky/release + jrM7EtbXW0LXEy/nT0NfWt/vDv7TOs/release + zu/release + 49 tfWt /u5ss/queues/nS1M2s0ru49tfWt/uz9s/wyrgjr4z/queues/ztcS5ss/queues/Qxc + queues/OjrNTau + queues + blocks = "http://www.2cto.com/uploadfile/2014/0209/20140209112907783.png" alt = "\"> physical on: structure:
Applicability: the Flyweight mode has strict application requirements. Its effectiveness depends largely on how it is used and where it is used. You can use the Flyweight mode when "All are true:

  • An application uses a large number of objects.
  • A large amount of storage overhead is caused by the use of a large amount of sex.
  • Most States of objects can be changed to external states.
  • If you delete the external state of an object, you can replace multiple groups of objects with fewer shared objects.
  • Applications do not rely on object identifiers. Because Flyweight objects can be shared, there is a clear concept of Tinning IANG, the logo test will return the true value structure: the following object diagram shows how to share flyweight
    Participants:
    • Flyweight (Glyph): describes an interface through which flyweight can accept and act on external states.
    • ConcreteFlyweight (Character): implements the Flyweight interface and adds storage space for internal states
    • UnsharedConcreteFlyweight (Row, Column): Not all Flyweight subclasses need to be shared. In some layers of the Flyweight object structure, the UnsharedConcreteFlyweight Object usually takes ConreteFlyweight as a byte and provides it with external information.
    • FlyweightFactory: Creates and manages flyweight objects. Ensure that flyweight is reasonably shared. When a user requests a flyweight, The FlyweightFactory object provides an existing instance or creates one that loves you (if it does not exist ). Collaboration:
      • When flyweight is executed, the desired state must be internal or external.
      • Instead of instantiating the ConcreteFlyweight class, you can only get the ConcreteFlyweight object from the FlyweightFactory object, which ensures that they are shared as appropriate. Effect: the memory is saved due to the following factors:
        • Share to reduce the total number of instances
        • Reduces the average number of internal states of Objects
        • When the external status is calculated, the efficiency is improved. When the external status is calculated, the amount saved reaches the maximum. Therefore, the Flyweight mode saves memory in two ways:
          • Share to reduce consumption of internal status
          • Use computing time in exchange for external state storage implementation: when implementing the Flyweight mode, pay attention to the following points:
            • Process external status
              • If different types of external States are the same as the number of objects before sharing, deleting an external State will not reduce storage consumption.
              • Ideally, the external State is calculated by a separate object, and the storage requirements of this structure are very small.
              • In the document editor example, you can use a separate structure to store layout information, rather than the font and type information of each character object.
              • Manage shared objects
                • Users cannot directly instantiate shared objects. Therefore, FlyweightFactory can help users find a specific Flyweight object.
                  Code example: the document editor mentioned above is used as an example to focus on font attributes. Class setting: Glyph class: The base class defined for Flyweight graphics objects. It belongs to the Composite class (see Composite in Composite mode). It has graphical attributes and can be drawn by itself.
                  class Glyph {public:    virtual ~Glyph();    virtual void Draw(Window*, GlyphContext&);    virtual void SetFont(Font*, GlyphContext&);    virtual Font* GetFont(GlyphContext&);    virtual void First(GlyphContext&);    virtual void Next(GlyphContext&);    virtual bool IsDone(GlyphContext&);    virtual Glyph* Current(GlyphContext&);    virtual void Insert(Glyph*, GlyphContext&);    virtual void Remove(GlyphContext&);protected:    Glyph();};
                  Character subclass stores a Character code:
                  class Character : public Glyph {public:    Character(char);    virtual void Draw(Window*, GlyphContext&);private:    char _charcode;};
                  GlyphContext class: To avoid assigning space to the font attribute of each Glyph, you can store this attribute externally in the GlyphContext object to implement: GlyphContext is an external store, it maintains a simple ing between Glyph and fonts. Usage: For any operation, if it needs to know the Glyph font in a given scenario, there will be a GlyphContext instance passed to it as a parameter. Then, you can query the GlyphContext to obtain the font information in the scenario. Note: When Using Glyph, the iteration and management operations of the Glyph subclass must update the GlyphContext.
                  class Glyph {public:    GlyphContext();    virtual ~GlyphContext();        virtual void Next(int step = 1);    virtual void Insert(int quantity = 1);    virtual Font* GetFont();    virtual void SetFont(Font*, int span = 1);private:    int _index;    BTree* _fonts;};
                  Btree: stores the glying between Glyph and font. Each node in the tree is marked with the length of the string, and the font information is transmitted to this string. The leaf node in the tree points to a font, and the internal string is divided into many sub-strings, each corresponding to a leaf node. The text information is as follows: The Btree structure may be shown in: assume that the index is traversed to 102. Goal 1: Set the "Time 12" font to "Time 12. The Code is as follows:
                  GlyphContext gc;Font* time12 = new Font("Times-Roman-12");Font* timeItalic12 = new Font("Times-Italic-12");// ...gc.SetFont(times12, 6);
                  The new B-tree structure is shown below (a change is indicated by a bold expression): Objective 2: use 12-point Times Itali before "CT" http://www.bkjia.com/kf/yidong/wp/ "target =" _ blank "class =" keylink "> WPX1szlzO2809K7uPa1pbTKRG9u" t (contains a space followed) before the word "wrong CT ). Assume that the gc is still in the index position and the code is 102:
                  gc.Insert(6);gc.SetFont(timesItalic12, 6);
                  The advantages of the changed Btree structure:
                  • When querying the current Glyph font, search down the Btree and add an index until the font of the current index is found.
                  • Because the font frequency is relatively low, the structure of the tree relative to Glyph is small.
                  • The storage is low, and the query time is not increased too much. The FlyweightFactory class is responsible for creating the Glyph class and ensuring that they are reasonably shared, that is, the management class of the Glyph class. Responsibilities: instantiate Character and other types of Glyph.
                    Const int NCHARCODES = 128; class GlyphFactory {public: GlyphFactory (); virtual ~ GlyphFactory (); virtual Character * CreateCharacter (char); virtual Row * CreateRow (); virtual Column * CreateColumn ();//... private: Character * _ character [NCHARCODES] ;}; // The _ character array contains pointers pointing to Character Glyphs indexed by letter code. The array is initialized to zero in the constructor. GlyphFactory: GlyphFactory () {for (int I = 0; I <NCHARCODES; ++ I) {_ character [I] = 0 ;}}; // search for a Character. If it exists, return the corresponding Glyph. If it does not exist, create the corresponding Glyph and put it into the array Character * GlyphFactory: CreateCharacter (char c) {if (! _ Character [c]) {_ character [c] = new Character (c);} return _ character [c];} // other operations only need to instantiate a new object each time the object is called, because non-character Glyph cannot be shared Row * GlyphFactory: CreateRow () {return new Row ;} column * GlyphFactory: CreateColumn () {return new Column ;}

                    Related mode:
                    • The Flyweight mode is usually combined with the combination mode to implement a logical hierarchy with a directed acyclic graph of the shared leaf node.
                    • Generally, it is best to use Flyweight to implement State and Strategy objects.
                      Reference: Design Pattern: Basis for reusable Object-Oriented Software

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.