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;
}
}
}