No nonsense C # design pattern Ten: Flyweight

Source: Internet
Author: User

Intention

The use of sharing technology to effectively support a large number of fine-grained objects.

Scene

There are usually a large number of fine-grained objects in a system or framework-level software system that is relatively low-level. Even if the object of fine intensity, if the use of a high order of magnitude will occupy a lot of resources. For example, the game may be used in countless places to use the model data, although the number of model objects will be very large, but in essence, different models may be so few.

At this point, we can introduce the meta pattern to share the same model object, which can greatly reduce the game's consumption of resources (especially memory).

Sample code

using System;

using System.Collections;

using System.Text;

using System.IO;

Namespace Flyweightexample

{

Class program

{

static void Mai N (string[] args)

{

Console.WriteLine (GC. Gettotalmemory (false));

Random rnd = new Random ();

ArrayList al = new ArrayList ();

for (int i = 0; i < 10000; i++)

{

string modelname = rnd. Next (2). ToString ();

Model model = Modelfactory.getinstance (). Getmodel (modelname);

//model model = new Model (modelname);

al. ADD (model);

}

Console.WriteLine (GC. Gettotalmemory (false));

Console.ReadLine ();

}

}

Class Model

{

PRivate byte[] data;

Public Model (string modelname)

{

data = file.readallbytes ("c:\\" + modelname + ". txt");

}

}

Class Modelfactory

{

Private Hashtable model List = new Hashtable ();

Private static Modelfactory instance

public static Modelfactory getinstance ()

{

if (instance = null)
br> instance = new Modelfactory ();

Return Instance

}

Public model Getmodel (string modelname)

{

Model mod El = Modellist[modelname] as Model;

if (model = = NULL)

Modellist.add (modelname, New Model (modelname));
return model;

}

}

}

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.