Object pooling的主要目的是提升程序性能。代码会先从Pool中取得已经建好的对象实例,如果Pool中没有对象实例才需要重新创建,以下代码是一个示例:
namespace ObjectPool
{
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Facotry facotry = new Facotry();
for (int i = 0; i < 10; i++)
{
var stu = facotry.GetStudent();
Console.WriteLine(stu.Name);
}
}
}
public class Facotry
{
private static int _PoolMaxSize = 3;
private static readonly Queue objPool = new Queue(_PoolMaxSize);
public Student GetStudent()
{
Student student;
if (Student.ObjectCounter >= _PoolMaxSize &&
objPool.Count > 0)
{
student = RetrieveFromPool();
}
else