什么是Flyweight模式?
享元模式(Flyweight Pattern)是一种软件开发中的设计模式,其主要解决的问题是通过类对象的共享,来避免大量创建拥有相同内容的对象的开销。可以简单理解用空间换取时间。
举例说明
一般的设计模式解释中都会用到如下两种场景来解释Flyweight Pattern:
1.GUI字处理软件中每个文字都是对象,缓存这些对象公用。
2.字符串驻留技术(String Interning)。
具体实现
复制代码 代码如下:
///
/// 享元模式Flyweight的实现
///
///
///
/// // C# 中数组是引用类型
/// var pool = new FlyweightObjectPool byte[] (() => new byte[65535]);
/// pool.Allocate(1000);
/// var buffer= pool.Dequeue();
/// // .. do something here ..
/// pool.Enqueue(buffer);
///
public class FlyweightObjectPool
{
private readonly Func
private readonly ConcurrentQueue
///
/// 享元模式Flyweight的实现
///
/// 分配缓存的方法
public FlyweightObjectPool(Func
{
_factoryMethod = factoryMethod;
}
///
/// 分配指定数量的对象
///
/// 指定的数量
public void Allocate(int count)
{
for (int i = 0; i < count; i++)
_queue.Enqueue(_factoryMethod());
}
///
/// 缓存一个对象
///
/// 对象
public void Enqueue(T buffer)
{
_queue.Enqueue(buffer);
}
///
/// 获取一个对象
///
///
public T Dequeue()
{
T buffer;
return !_queue.TryDequeue(out buffer) ? _factoryMethod() : buffer;
}
}
使用举例
复制代码 代码如下:
class Program
{
static void Main(string[] args)
{
var pool = new FlyweightObjectPool
pool.Allocate(1000);
var buffer = pool.Dequeue();
// .. do something here ..
pool.Enqueue(buffer);
}
}



