Enjoy meta mode

Source: Internet
Author: User

1.1.2 Body

Figure 1 Enjoy meta-mode (FLYWEIGHT) structure diagram

Enjoy meta mode (Flyweight): Use shared technology to effectively support a large number of fine-grained objects.

Abstract enjoy meta-role (Flyweight): This role is a superclass of all the specific classes of the class, specifying the public interfaces or abstract classes that need to be implemented for these classes. Operations that require external states (External State) can be passed in through the parameters of the method. The interface of the abstract element makes it possible, but does not force the subclass to share, so not all of the objects are shareable.

Specific Concreteflyweight role: implements the interface defined by the abstract-privilege meta-role. If there is an internal state, you must be responsible for providing storage space for the internal state. The internal state of the enjoyment meta-object must be independent of the environment in which the object is located, allowing the object to be shared within the system. Sometimes the specific enjoy meta-role is also called the simple specific enjoy meta role, because the compound to enjoy the meta-role is composed of simple and specific to the meta-role through the composite .

Compound Unsharableflyweight Role: the objects represented by the compound-enjoy meta-role are not shareable, but a composite-object can be decomposed into a combination of multiple, simple-to-enjoy meta-objects. The compound-privilege role is also known as a non-shareable object of enjoyment. This role is rarely used.

Enjoy meta-factory (Flyweightfactoiy) Role: This role is responsible for creating and managing the rewards role. This role must ensure that the sharing meta-object can be properly shared by the system. When a client object requests an object for a privilege, the enjoy Meta factory role needs to check to see if there is an eligible object in the system, and if it does, it should provide the existing one, and if there is not an appropriate element of the object in the system, The enjoy meta-factory role should create a new and appropriate sharing object.

Client role: This role also needs to store the external state of all the objects of the privilege itself.

Internal state and external 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, and the non-shared state is called the external state as the environment changes.

Now let's use an object-oriented text editor design to illustrate the application of the enjoy meta-mode. Suppose we want to design a text editor, and it must create a character object to represent each character in the document, now let's consider what information the character object holds. such as: font, font size and location, etc. information.

A document typically contains many character objects that require large amounts of memory. It is worth noting that the general characters are composed of numbers, letters and other characters (they are fixed, known), these character objects can share information such as font and font size, and now their proprietary properties are only left position, each character object just keep their position in the document is OK, By analyzing we have reduced the memory requirements of the editor.

Figure 2 sharing objects with the Flyweight mode

<summary>///the ' Flyweight ' class.///</summary>public class character{    //intrinsic    State protected char _symbol;    protected int _size;    protected string _font;    Extrinsic state    protected Position _position;    public void Display (Position Position)    {        Console.WriteLine (            String.Format ("Symbol: {0} Size: {1} Font: {2} Position: {3} {4} ",            _symbol, _size, _font, position._x, position._y));}    }

Now we have defined a word Fu Yuan class in which the match, font, and font size are internal and the position is the external state.

<summary>///A ' concreteflyweight ' class///</summary>public class charactera:character{public    Charactera ()    {        _symbol = ' A ';        _size = ten;        _font = "Song Body";        _position = new position (0, 1);}    }

We then define the privilege class for the specific character a, and initialize the internal state symbol, font, and font size, and the other characters B to Z are similar.

Figure 3 The design of the specific enjoy meta-mode (concreteflyweight)

<summary>///the ' flyweightfactory ' class///</summary>public class characterfactory{//Keeps the Char    Acter object by specifying Key/value.    Private Dictionary<char, character> _characters = new Dictionary<char, character> ();            Public Character This[char Key] {get {Character Character = null;            Checked the character whether existed or not,//if the character existed and then directly returns,            Otherwise, instantiates a character object. if (_characters.            ContainsKey (key)) {character = _characters[key]; } else {string name = this. GetType (). Namespace + "." + "Character" + key.                    ToString ();                character = Activator.CreateInstance (Type.GetType (name)) as character; _characters.            ADD (key, character); } rEturn character; }    }}

Now we have defined a character factory, using a Dictionary<tkey, tvalue> to save the character object, use the character value to find whether the character object has already been created, and if the character object that is found already exists, return the object directly, and vice versa, create a Character object instance.

<summary>///the client.///</summary>///<param name= "args" >the Args.</param>[stathread] static void Main (string[] args) {    application.enablevisualstyles ();    Application.setcompatibletextrenderingdefault (false);    Application.Run (New Frmflyweight ());    String text = "Abzabbzz";    char[] Letters = text. ToCharArray ();    var characterfactory = new Characterfactory ();    Creates random position ranges 0 to.    var rd = new Random ();    foreach (char c in letters)    {        Character Character = characterfactory[c];        var p = new Position (rd. Next (0, +), RD. Next (0, +));        Character. Display (P);    }    Console.readkey ();}

Figure 4 Enjoy meta-mode (concreteflyweight) test results

Let's then implement a drawing program for the meta-mode, assuming that our program draws a variety of circles, and that the properties of the circle have shapes, positions, and colors, where the shape and color are internal, and the position is the external state.

Design Analysis:

1. Provide an abstract class shape that allows specific shapes such as: circle to inherit from it

2. Define a location structure chart to record the location of each graphic

3. Design an exclusive meta-graphics factory to create graphical objects

The above is the design of the drawing program of our enjoy meta-mode, then let us realize the drawing program to enjoy meta-mode!

<summary>///Shape can be inherited by Circle, retangle or triangle and so forth.///includes a color property a nd Draw methods.///</summary>public abstract class shape{public    color color {get; set;}    public abstract void Draw (graphics graphics, Position Position);}

The above schematic code defines an abstract class shape, and our specific graph must inherit from that class.

<summary>///Circle implements shape.///</summary>public class circle:shape{public    Circle (Color C Olor)    {        color = color;    }    <summary>//    draws circle with the specified graphics and position.    </summary>//    <param name= "Graphics" >the graphics.</param>//    <param name= " Position ">the position of circle.</param> public    override void Draw (graphics graphics, position position) c10/>{        var pen = new Pen (Color);        Graphics. DrawEllipse (pen, position. X-position. R,            position. Y-position. R,            position. R, position. R);}    }

We then define the specific graph class circle, which implements the draw () method to implement the circle using the graphics call DrawEllipse () method.

///<summary>///Generate the position of concrete shape.///</summary>public struct    position{private int _x;    private int _y;    private int _r;        Public Position GetPosition (Form form) {var rd = new Random (); _x = Rd. Next (0, form.        Width); _y = Rd. Next (0, form.        Height); float R = _x < _y?        _x: _y; _r = Rd.        Next (0, (int) r);    return this; } public Position (graphics graphics, int x, int y, int r) {if (X > Graphics.        Dpix) throw new ArgumentOutOfRangeException ("X"); if (Y > graphics.        DPIY) throw new ArgumentOutOfRangeException ("Y"); if (R > Graphics. Dpiy && r > Graphics.        Dpix) throw new ArgumentOutOfRangeException ("R");        _x = x;        _y = y;    _r = R;    } public int X {get {return _x;}    } public int Y {get {return _y;}    } public int R {get {return _r;} }}

We then define the sharing factory, which is responsible for creating the drawing object, and if the drawing object does not exist, it is returned directly to the drawing object.

<summary>///The flyweight factory///generates the instance of shape if object not exists,///Otherwish returns The object directly.///</summary>public class shapefactory{    //Saves The Shape object in Dictionary<color, shape>    private static readonly Dictionary<color, shape> Shapes =        new Dictionary<color, shape> () ;    Gets the object in Dictionray.    Public Shape This[color Key]    {        get        {            shape shape = null;            If the object exists return directly.            Otherwish generates anew one.            if (Shapes.containskey (key))            {                shape = Shapes[key];            }            else            {                shape = new Circle (key);                Shapes.add (key, shape);            }            return shape;}}    }

Now that we have completed the enjoy Meta graph class, because the external state of the graph includes position and color, we create a random position by random function, we want to design a color picker to provide the user with the choice of custom colors.

Figure 5 Color Picker Design

Due to the time of the relationship we have set the color swatch interface, then let us realize the specific function of the color swatch.

First we create a new user custom control named Colorpanel, and then we want to handle the event where the user clicks on the color selection.

Sets the default color.private color _color = color.black;public delegate void Colorchangedhandler (object sender, Color Changedeventargs e);p ublic event Colorchangedhandler colorchanged;///<summary>///raises the <see cref= "E: Colorchanged "/> event.///</summary>///<param name=" E ">the color Changed event Arguments.</param >protected virtual void oncolorchanged (Colorchangedeventargs e) {    if (null! = colorchanged)        colorchanged ( This, e);}

The above schematic code defines a delegate Colorchangedhandler, when the color value is found to change the corresponding specific processing method and an event Colorchangedhandler, in fact, the event is the encapsulation of the delegate, as if the relationship between the fields and attributes, Please see here and here for details of the delegates and events.

Figure 6 Custom Events

Let's first introduce the type of EventArgs. In fact, this class does not have much functionality, it is mainly as a base class for other classes to implement specific functions and definitions, when we customize the event parameters must inherit from the class.

Now go back to our custom event parameter, Colorchangedeventargs, which contains the method that initializes the color value and the property that gets the color value.

<summary>///the color Changed event arguments.///</summary>public class Colorchangedeventargs:eventar gs{    private readonly Color _color;    <summary>//    Initializes a new instance of the <see cref= "Colorchangedeventargs"/> class.    </summary>    //<param name= "COLOR" >the color.</param> public    Colorchangedeventargs ( Color color)    {        _color = color;    }    <summary>//    Gets the color.    </summary> public    Color color    {        get {return _color;    }}

Now that we have finished the basic function of the color swatch, we just need to add the color picker control to our application.

Figure 6 Enjoy meta-mode drawing program Interface

Because of the time relationship we have designed the interface of the program, and then let us implement a series of event processing methods.

<summary>///Handles The Click event of the Btndrawcircle control.///</summary>///<param name= "sender  ">the source of the event.</param>///<param name=" E ">the <see cref=" System.EventArgs "/>///  Instance containing the event data.</param>private void Btndrawcircle_click (object sender, EventArgs e) {Graphics        Graphics = Graphics.fromimage (_drawarea);    Gets Shape object with specified color in flyweight object.    Shape shape = _factory[colorpanel1.color]; Shape. Draw (graphics, _position.    GetPosition (this)); This. Invalidate ();} <summary>///Handles The Click event of the Btnclear control.///</summary>///<param name= "Sender" > The source of the event.</param>///<param name= "E" >the <see cref= "System.EventArgs"/>//instance con Taining the event data.</param>private void Btnclear_click (object sender, EventArgs e) {Graphics graphics = Graph Ics.    FromImage (_drawarea); Graphics. CleaR (Color.skyblue); Graphics.    Dispose (); This. Invalidate ();}

Above we define the method of handling the drawing click and clear the graph, when the user chooses the color value, our program obtains the object instance in the the the Enjoyment meta factory, this object may be new, possibly already exists.

Figure 7 Drawing program Effects

1.1.3 Summary

In this paper, we give a typical application example of the model of the enjoyment of meta-mode to introduce the specific application of the model, but it is often used in the development of the system to solve the system performance problem.

Applicability

The effectiveness of the flyweight pattern is largely dependent on how it is used and where it is used. Use flyweight mode when the following conditions are true.

1) An application uses a large number of objects.

2) due to the use of a large number of objects, resulting in a large storage overhead.

3) Most of the state of an object can become an external state.

4) If you delete an object's external state, you can replace many group objects with a relatively small number of shared objects.

5) The application does not rely on object identification.

Advantages and Disadvantages

1) Enjoy meta mode makes the system more complex. In order for objects to be shared, some States need to be externally instantiated, which complicates the logic of the program.

2) The enjoy meta-mode will allow the state of the meta-object to be instantiated, while reading the external state makes the run time slightly longer.

Enjoy meta mode

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.