C + + Design pattern programming Flyweight mode structure detailed _c language

Source: Internet
Author: User

The problem arises from the issue of the pattern of the privilege:

In the design of object-oriented system, creating objects is the most common operation. There is a problem here: If an application uses too many objects, it can cause a lot of storage overhead. In particular, for a large number of lightweight (fine-grained) objects, such as in the design process of the document editor, if we create an object for no letters, the system may waste storage overhead because of a large number of objects. For example, a letter "a" appears in the document 100,000 times, in fact, we can let these 10,000 letters "a" share an object, of course, because the letter "a" in different places may have different display effects (such as font and size settings are different), in this case we can divide the object's state into " External state and internal state, the state that can be shared (unchanged) is stored as an internal state in the object. External objects (such as the font, size, etc. mentioned above) can be passed to the object at the appropriate time, such as the font, size, and so on when the object is displayed.

role: the use of shared technology to effectively support a large number of fine-grained objects.

Internal state intrinsic and external state extrinsic:

1 in flyweight mode, the most important thing is to decompose the object into intrinsic and extrinsic two parts.

2 internal state: The shared part that is inside the object of the element and does not change with the environment, can be called the internal state of the object of the privilege

3 external state: and changes in the context of the environment, depending on the application environment, or real-time data, these can not be shared things is the external state.

4 The difference between the internal state and the external state:
In flyweight mode applications, the external state attribute is usually modified, while the internal state attribute is generally used for reference or calculation.
The state required for flyweight execution must be internal or external. The internal state is stored in the Concreteflyweight object, while the external state is stored or computed by the client object. When the user invokes the action of the flyweight object, the state is passed to it.

Take word processing software for example:

The internal state is stored in flyweight, which contains information that is independent of the flyweight scene, which allows flyweight to be shared. such as character code, character size ...

The external state depends on the flyweight scene and changes according to the scene, so it is not shared. The user object is responsible for passing the external state to the flyweight when necessary, such as character position, character color ...

UML diagram:

Analytical:
Flyweight: The base class of the privilege class, defining an interface through which Flyweight can accept and act on the external state.

Concreteflyweight: Implements the flyweight interface and adds storage space for internal state (if any). The Concreteflyweight object must be shareable. The state it stores must be internal (intrinsic), that is, it must be independent of the scene of the Concreteflyweight object.

Unsharedconcreteflyweight: Not all of the flyweight subclasses need to be shared. The flyweight interface makes sharing possible, but it does not force sharing. At some levels of the flyweight object structure, the Unsharedconcreteflyweight object usually takes the Concreteflyweight object as a child node.

Flyweightfactory:

1 Create and manage flyweight objects.

2 ensure reasonable sharing of flyweight. When a user requests a flyweight, the Flyweightfactory object provides an instance that has already been created or creates one (if it does not exist)

Client
1) Maintain a reference to the flyweight.

2) calculates or stores the external state of a (multiple) flyweight.

Analysis:
The privilege pattern avoids the overhead of a large number of very similar classes. In programming, it is sometimes necessary to generate a large number of fine-grained class instances to represent data. If you can find these instance data are basically the same except for a few parameters. It is sometimes possible to drastically reduce the number of instantiated classes. If you can move those parameters outside the class instance and pass them in when the method is called, you can drastically reduce the number of individual instances by sharing.

For example, in the design process of the document editor, if we create an object for no letters, the system may waste storage overhead because of a large number of objects. For example, a letter "a" appears in the document 100,000 times, in fact, we can let these 10,000 letters "a" share an object, of course, because the letter "a" in different places may have different display effects (such as font and size settings are different), in this case we can divide the object's state into " External state and internal state, the state that can be shared (unchanged) is stored as an internal state in the object. External objects (such as the font, size, etc. mentioned above) can be passed to the object at the appropriate time, such as the font, size, and so on when the object is displayed.

The internal state of the flyweight is shared, and flyweightfactory is responsible for maintaining a flyweight pool (the object that holds the internal state), and when the client requests a shared flyweight, the factory first searches the pool for any applicable , if there is, factory simply returns to send out this object, otherwise, create a new object, join the pool, and return to send out this object. The pool is called an internal state by setting a buffer for duplicate or shareable objects and properties. These internal states are generally not modifiable, that is, after the first object, the property is created, it will not be modified (otherwise meaningless).

Flyweight shares the internal state of an object, creates an instance for each internal state, and uses a singleton pattern for the internal state.

Users should not instantiate the Concreteflyweight class directly, but only get Concreteflyweight objects from the Flyweightfactory object, which ensures that they are properly shared.

Storage savings are determined by the following factors:
1 The total number of instances decreased because of sharing
2 The average number of internal state of the object
3 whether the external state is calculated or stored

Implementation Essentials
1) Enjoy the Yuan factory maintenance of a case table.

2) The status of the unshared state needs to be maintained externally. To delete an external state: the availability of the pattern depends to a large extent on whether it is easy to recognize the external state and remove it from the shared object.

3) The role of the privilege can be abstracted according to the requirement.

4 Manage Shared objects: reference count and garbage collection ...

When to use
1 If an application uses a large number of objects, and a large number of these objects cause a lot of storage costs should be considered to use;

2 There is also a majority of the object's State can become an external state, if you delete the external state of the object, you can use a relatively small number of shared objects to replace many groups of objects, you can consider the use of the pattern of the usage.

3 The system has a large number of fine-grained objects that consume a lot of memory, and there is no difference to the outside world (or, after modification, there can be no difference).

In the document editor example, if a character corresponds to an object, the object that a document will hold is very large and consumes a lot of memory. The actual composition of the document is limited by the combination and arrangement of the characters. So you need to share and share the basic characters so that the character objects become limited.

Example:
The element mode is used extensively in the editor system. A text editor often provides a wide variety of fonts, and the usual practice is to make each letter a single object. The intrinsic state of the object is the letter, and other information, such as the position of the letter in the text and the style of the font, is the outer state. For example, the letter a may appear in many parts of the text, although the position of the letters a differs from the font style, but all of these places use the same alphabetic object. As a result, alphabetic objects can be shared throughout the system.

Flyweight pattern--the real world example using System;

Using System.Collections; namespace DoFactory.GangOfFour.Flyweight.RealWorld {//Mainapp Test application class Mainapp {static void Main (
   ) {//Build a document with text string document = "AAZZBBZB"; char[] chars = document.

   ToCharArray ();

   Characterfactory f = new characterfactory ();

   extrinsic state int pointsize = 10;
    For each character use a Flyweight object foreach (char c in chars) {pointsize++;
    Character Character = F.getcharacter (c); Character.
   Display (pointsize);
  }//wait for user console.read ();

  }//"Flyweightfactory" class Characterfactory {private Hashtable characters = new Hashtable (); Public Character Getcharacter (char key) {//Uses "lazy initialization" Character Character = Characters[key] As
   Character;
 if (character = null) {switch (key) {case ' A ': character = new Charactera ();    Case ' B ': character = new Characterb ();
      Break Case ' Z ': character = new Characterz ();
    Break } characters.
   ADD (key, character);
  return character;
  }//"Flyweight" abstract class Character {protected char symbol;
  protected int width;
  protected int height;
  protected int ascent;
  protected int descent;

  protected int pointsize;
 public abstract void Display (int pointsize);  }//"Concreteflyweight" class Charactera:character {//Constructor public Charactera () {This.symbol =
   ' A ';
   This.height = 100;
   This.width = 120;
   This.ascent = 70;
  this.descent = 0;
   public override void Display (int pointsize) {this.pointsize = pointsize;
  Console.WriteLine (This.symbol + "(pointsize" + this.pointsize + ")"); }//"Concreteflyweight" class Characterb:character {//Constructor public Characterb () {This.symbo
   L = ' B ';
   This.height = 100;
   This.width = 140; This.asceNT = 72;
  this.descent = 0;
   public override void Display (int pointsize) {this.pointsize = pointsize;
  Console.WriteLine (This.symbol + "(pointsize" + this.pointsize + ")"); 

 }//C, D, E, etc. "Concreteflyweight" class Characterz:character {//Constructor public Characterz () {this.symbol = ' Z '
   ;
   This.height = 100;
   This.width = 100;
   This.ascent = 68;
  this.descent = 0;
   public override void Display (int pointsize) {this.pointsize = pointsize;
  Console.WriteLine (This.symbol + "(pointsize" + this.pointsize + ")");

 }
 }
}

Output:

Advantages and disadvantages of the meta pattern

The advantage of the privilege mode is that it drastically reduces the number of objects in memory. But the price it pays for doing this is high:
The pattern of the privilege makes the system more complex. In order for objects to be shared, some states need to be externalized, which complicates the logic of the program.
The pattern of the privilege is externalized the state of the object, while reading the external state makes the running time slightly longer.

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.