Design Mode (C #)-flyweight Pattern)

Source: Internet
Author: User

The metadata mode is a design mode that prevents the appearance of a large number of identical or similar objects. Generally, the objects that appear cannot be the same. They may be very similar, but some of them may be in different States, in this way, we can abstract the same parts of them and encapsulate them. They are called inner states, and then different places, called external States. We can add them to objects through some methods, in this way, the object can be reused without creating so many objects.

 

# Region metadata Mode

# Region requirements
// Overview
// The Object-oriented Thinking solves the abstract problem well, and generally does not have performance problems. However, in some cases, the number of objects may be too large, resulting in the runtime cost. So how can we avoid a large number of fine-grained objects without affecting customers?ProgramAre operations performed in an object-oriented manner?
// Intention
// Use the sharing technology to effectively support a large number of fine-grained objects. [Gof design patterns]
# Endregion

# Region Case Study
// Considering such a word processing software, the object to be processed may have a single character, a paragraph consisting of characters and the entire document. According to the object-oriented design idea and the composite mode, whether it is a character or a paragraph, a document should be viewed as a single object. Here, only a single character is taken into account, and paragraphs, documents, and other objects are not considered.
# Endregion

# Region usage
// Effect and key points
// 1. Object-oriented solves the abstract problem, but as a program entity running on the machine, we need to consider the cost of the object. The flyweight design model mainly solves the problem of object-oriented cost, and generally does not touch the abstract problem of object-oriented.
// 2. flyweight uses Object sharing to reduce the number of objects in the system, thus reducing the memory pressure on the system caused by fine-grained objects. In specific implementation, you must pay attention to processing the object status.
// 3. The advantage of the metadata mode is that it greatly reduces the number of objects in the memory. However, it pays a very high price to achieve this: the Yuan-sharing model makes the system more complex. In order for objects to be shared, some States need to be externalized, which complicate the logic of the program. In addition, it externalizes the state of the object, and reads the external State to slightly extend the running time.
// Applicability
// When all the following conditions are met, you can consider using the enjoy mode:
// 1. A system has a large number of objects.
// 2. These objects consume a large amount of memory.
// 3. Most of these object states can be externalized.
// 4. These objects can be divided into many groups according to the inherent state. When the external object is removed from the object, each group can be replaced by only one object.
// 5. The software system does not depend on the identity of these objects. In other words, these objects can be undistinguished.
// The system that meets the preceding conditions can use a metadata object. Finally, you need to maintain a table that records all the existing metadata in the system in the metadata-sharing mode, which consumes resources. Therefore, the metadata mode should be used only when there are enough metadata instances available for sharing.
// Summary
// The flyweight mode solves the memory overhead caused by a large number of fine-grained objects, which is not commonly used in actual development, however, it is very effective as a means to improve the underlying performance.
# Endregion

 

Example

There is a message object class. Some objects operate on them using the insert () and get () methods. Now we need to use the sharing technology to support these objects.

Messagemodel

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace pattern. flyweight
{
/** // <Summary>
/// Message object class
/// </Summary>
Public class messagemodel
{
/** // <Summary>
/// Constructor
/// </Summary>
/// <Param name = "MSG"> message content </param>
/// <Param name = "PT"> message release time </param>
Public messagemodel (string MSG, datetime pt)
{
This. _ message = MSG;
This. _ publishtime = pt;
}

Private string _ message;
/** // <Summary>
/// Message content
/// </Summary>
Public String message
{
Get {return _ message ;}
Set {_ message = value ;}
}

Private datetime _ publishtime;
/** // <Summary>
/// Message release time
/// </Summary>
Public datetime publishtime
{
Get {return _ publishtime ;}
Set {_ publishtime = value ;}
}
}
}

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace pattern. flyweight
{
/** // <Summary>
/// Action message abstract class (flyweight)
/// </Summary>
Public abstract class implements actmessage
{
/** // <Summary>
/// Get message
/// </Summary>
/// <Returns> </returns>
Public abstract list <messagemodel> get ();

/** // <Summary>
/// Insert Message
/// </Summary>
/// <Param name = "mm"> message object </param>
/// <Returns> </returns>
Public abstract bool insert (messagemodel mm );
}
}

Sqlmessage

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace pattern. flyweight
{
/** // <Summary>
/// SQL message (concreteflyweight)
/// </Summary>
Public class sqlmessage: abstractmessage
{
/** // <Summary>
/// Get message
/// </Summary>
/// <Returns> </returns>
Public override list <messagemodel> get ()
{
List <messagemodel> L = new list <messagemodel> ();
L. Add (New messagemodel ("obtain message through SQL", datetime. Now ));

Return L;
}

/** // <Summary>
/// Insert Message
/// </Summary>
/// <Param name = "mm"> message object </param>
/// <Returns> </returns>
Public override bool insert (messagemodel mm)
{
//CodeOmitted
Return true;
}
}
}

 

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace pattern. flyweight
{
/** // <Summary>
/// Message (concreteflyweight) in XML format)
/// </Summary>
Public class xmlmessage: abstractmessage
{
/** // <Summary>
/// Get message
/// </Summary>
/// <Returns> </returns>
Public override list <messagemodel> get ()
{
List <messagemodel> L = new list <messagemodel> ();
L. Add (New messagemodel ("Get message in XML format", datetime. Now ));

Return L;
}

/** // <Summary>
/// Insert Message
/// </Summary>
/// <Param name = "mm"> message object </param>
/// <Returns> </returns>
Public override bool insert (messagemodel mm)
{
// Code omitted
Return true;
}
}
}

Messagefactory

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace pattern. flyweight
{
/** // <Summary>
/// Message Factory (flyweightfactory)
/// </Summary>
Public class messagefactory
{
Private dictionary <string, abstractmessage> _ messageobjects = new dictionary <string, abstractmessage> ();

/** // <Summary>
/// Obtain the message object
/// </Summary>
/// <Param name = "key"> key </param>
/// <Returns> </returns>
Public abstractmessage getmessageobject (string key)
{
Abstractmessage messageobject = NULL;

If (_ messageobjects. containskey (key ))
{
Messageobject = _ messageobjects [Key];
}
Else
{
Switch (key)
{
Case "XML": messageobject = new sqlmessage (); break;
Case "SQL": messageobject = new xmlmessage (); break;
}

_ Messageobjects. Add (Key, messageobject );
}

Return messageobject;
}
}
}

 

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;

Using pattern. flyweight;

Public partial class flyweight: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
String [] ary = new string [] {"XML", "SQL "};

Messagefactory = new messagefactory ();

Foreach (string key in ary)
{
Abstractmessage messageobject = messagefactory. getmessageobject (key );

Response. Write (messageobject. insert (New messagemodel ("insert", datetime. Now )));
Response. Write ("<br/> ");
Response. Write (messageobject. Get () [0]. Message + "" + messageobject. Get () [0]. publishtime. tostring ());
Response. Write ("<br/> ");
}
}
}

Running result

True

Obtain message 22:20:38 through SQL

True

Get message 22:20:38 in XML format

Reference

Http://www.dofactory.com/Patterns/PatternFlyweight.aspx

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.