C # design mode-Metadata Mode

Source: Internet
Author: User

C # design mode-Metadata Mode
Preface recently, I began to focus on the design pattern, mainly to make the code written by myself highly reusable and ensure code reliability. The so-called design pattern is defined by me as a summary of code design experiences that have been repeatedly used, known to most people, classified and catalogued. There is no doubt that the design pattern is win-win for others and the system; The design pattern enables code compilation to be truly engineered; The design pattern is the cornerstone of the software engineering, just like the structure of the building. Why do we advocate "Design Pattern )"? The root cause is to reuse code and increase maintainability. So this time we will study the design patterns, and finally use the C # language to implement these design patterns as an example to deeply understand the essence. Define the metadata mode: it uses shared objects to minimize memory usage and share information with as many similar objects as possible; it is suitable for a large number of objects that use unacceptable large amounts of memory due to repetition. Some statuses of objects are usually shared. A common practice is to put them in an external data structure and pass them to the user when necessary. In the singleton mode mentioned earlier, a class has only one unique object. That is to say, no matter how many times it is new, you only need to create an object for this class. If the singleton mode is not used, each time a new object is created, a large number of repeated objects are generated. When these objects consume a large amount of resources, the mutual resource grab delay occurs. At this time, the metadata mode can help solve such problems. The purpose of the feature metadata mode is to provide application performance by sharing a large number of fine-grained objects and saving performance consumption for repeatedly creating object instances in the system. How can this problem be solved? It actually has the following meanings: 1. When there are many instances of an object type in our system. 2. When these instances are required to be classified, it is found that there are very few actually different categories. For example, in many scenarios in our life, when we use the Pinyin input method, if we say every word is a new object instance operation, then the instance in the memory is terrible, at this time, can we consider creating these duplicate fonts in the memory only once, but by reusing the object to organize some content that may contain multiple characters? Advantages and disadvantages: 1. reduces the number of objects in the system, thus reducing the pressure on memory caused by fine-grained objects in the system. Disadvantages: 1. In order to share objects, some States need to be externalized, which makes the logic of the program more complicated and the system more complicated. II. The metadata mode externalizes the state of the object, while reading the external State leads to a slightly longer running time. Solution: Pic86 the metadata sharing mode uses a tree structure to represent the relationship between parts and the whole, in this way, the client can treat part of objects in the same way as the whole objects combined by them. The metadata-sharing mode is mainly composed of three parts: the metadata class, the specific metadata class, and the metadata-sharing factory class. Copy the Code # region Client call // <summary> // Client call // </summary> class Client {static void Main (string [] args) {// initialize the metadata factory FlyweightFactory factory = new FlyweightFactory (); // determine whether object 1 has been created. If yes, use the created object Flyweight fa = factory. getFlyweight (0); if (fa! = Null) {// use the external State as the method call parameter of the object. fa. operation ();} // determines whether the letter B Flyweight fb = factory has been created. getFlyweight (1); if (fb! = Null) {fb. Operation () ;}// determine whether the letter C Flyweight fc = factory. GetFlyweight (2); if (fc! = Null) {fc. Operation () ;}// determine whether the letter D Flyweight fd = factory. GetFlyweight (3); if (fd! = Null) {fd. operation ();} else {Console. writeLine ("No objects exist in the resident pool 4"); // at this time, you need to create an object and put it in the resident pool ConcreteFlyweight d = new ConcreteFlyweight ("fourth object"); factory. flyweights. add (d);} Console. read () ;}# endregion # region metadata factory, which is responsible for creating and managing metadata objects /// <summary> // metadata factory, creates and manages metadata objects. // </summary> public class FlyweightFactory {public List <Flyweight> flyweights = new List <Flyweight> (); public FlyweightFactory () {fl Yweights. add (new ConcreteFlyweight ("first object"); flyweights. add (new ConcreteFlyweight ("second object"); flyweights. add (new ConcreteFlyweight ("third object");} public Flyweight GetFlyweight (int key) {Flyweight flyweight; if (key> = flyweights. count) {Console. writeLine ("No objects exist in the resident pool" + (key + 1); flyweight = new ConcreteFlyweight ("Number" + (key + 1) + "object ");} else {flyweight = flyweights [key];} return flyweight ;}} # Endregion # region abstract metadata class, which provides methods for a specific metadata class. // <summary> // abstract metadata class, provides methods for the specific metadata class. // </summary> public abstract class Flyweight {public abstract void Operation ();} # endregion # region's specific metadata object // <summary> // The specific metadata object /// </summary> public class ConcreteFlyweight: Flyweight {private string intrinsicstate; // ConcreteFlyweight (string innerState) {this. intrinsicstate = innerState ;}/// <Summary> // instance method of the metadata class /// </summary> /// <param name = "extrinsicstate"> external State </param> public override void Operation () {Console. writeLine ("called specific object: {0}", intrinsicstate) ;}# there are two important methods for the DbConnectionPool class of the simple database connection pool that the endregion replication Code uses the metadata mode; getConnection (), get an object from the object pool, returnConnection (), and return the object to the object pool. We implement an object pool using two hash tables, freeConnections and busyConnections. the busyConnections hash table contains all objects in use, and the freeConnections hash table contains all objects that are not used and can be used at any time. Copy the code public interface DbConnectionPool {// set the number of connections stored in the connection pool public void SetMaxConns (int numConnections); // set to open or close the connection pool public void SetConnWitch (string Switch ); // generate the Connection pool public void initConnPool (); // obtain the Connection pool from the Connection pool public Connection getConnection (); // return the Connection to the Connection pool public void returnConnection (); // destroy the connection pool public void destroyConnPool ();} copy the code and copy the code public class GdDbConnectionPool: DbConnectionPool {private static str Ing connectionString = @ "server = (local); Trusted Connection = yes; database = myDB"; // default Connection pool size static const int defamaxmaxconnections = 10; // store the currently idle connections and the idle pool private List <Connnection> freeConnections; // store the currently used connection private List <Connnection> busyConnections; // set the connection pool size private int maxConnections; // constructor public GdDbConnectionPool (int numConnections) {maxConnections = numConnections; freeConnections = null; BusyConnections = null ;} # region: Obtain database connections /// <summary> /// obtain database connections /// </summary> /// <returns> </returns> public Connection getConnection () {if (freeConnections = null) {return "the connection pool has not been created";} object o = null; lock (this) {try {foreach (DictionaryEntry myEntry in freeConnections) {o = myEntry. key; unlocked. remove (o); if (Validate (o) {locked. add (o, now); return o;} else {Expire (O); o = null ;}}// gets the idle pool Connection conn = (Connection) freeConnections. get (0); freeConnections. remove (o); busyConnections. add (o); return o ;}# endregion # region generate connection pool // <summary> // generate connection pool // </summary> public void initConnPool () {freeConnections = new freeConnections (maxConnections); busyConnections = new busyConnections (maxConnections); for (int I = 0; I <maxConnections; I ++) {free Connections. add ();}} # endregion # region destroys the returned connection from the busy pool /// <summary> /// destroys the returned connection from the busy pool /// </summary> public void returnConnection () {busyConnections conn = (Connection) busyConnections. get (); if (conn = null) throw new Exception ("no connection found in the busy pool"); busyConnections. remove (); freeConnections. add (conn) ;}# endregion} copying code is an extremely important concept in the multi-threaded world of enterprise computing. It is widely used in databases, message queues, Web servers, and other well-known applications. Developers who develop multi-threaded applications must be particularly aware of their synchronization concepts. Instead of making every object thread-safe, the system is overwhelmed. Instead, we should pay attention to deadlocks and solve as many deadlocks as possible at the beginning of program design. It is equally important to understand the performance bottleneck of synchronization because it affects the overall performance of applications.

Related Article

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.