運用共享技術有效支援大量細粒度物件。
底層系統/框架常存在大量細粒度物件。遊戲中無數位置使用模型資料,數量雖多但本質上僅有幾種模型。引入 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 // Flyweight
{
private byte[] _data;
public Model(string modelName)
{
_data = File.ReadAllBytes(@"c:\" + modelName + ".txt");
}
}
class ModelFactory // Flyweight Factory + Singleton
{
private Hashtable _modelList = new Hashtable();
private 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 快速查找已存在模型GC.GetTotalMemory() 量化記憶體效益| 狀態類型 | 範例 | 儲存位置 |
|---|---|---|
| 內部狀態 | 模型資料、紋理、幾何資訊 | Flyweight 物件內部(共享) |
| 外部狀態 | 座標、旋轉、縮放、顏色色調 | Client 管理,渲染時傳入 |