運用共享技術有效支援大量細粒度對象。
底層系統或框架常存在大量細粒度對象。遊戲中無數處使用模型數據,模型對象雖多但本質上只有幾種。引入 Flyweight 共享相同模型,大幅降低記憶體消耗。
using System;
using System.Collections;
using System.Text;
using System.IO;
namespace FlyweightExample
{
class Program
{
static void Main(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
{
byte[] data;
public Model(string modelName) => data = File.ReadAllBytes($@"c:\{modelName}.txt");
}
class ModelFactory
{
Hashtable modelList = new Hashtable();
static ModelFactory instance;
public static ModelFactory GetInstance()
{
if (instance == null) instance = new ModelFactory();
return instance;
}
public Model GetModel(string modelName)
{
Model model = modelList[modelName] as Model;
if (model == null) modelList.Add(modelName, new Model(modelName));
return modelList[modelName] as Model;
}
}
}
Hashtable 管理享元實例。獲取時優先回傳已有實例,避免重複載入。