Object pool is a box of objects that contains a list of other objects that are ready to be used.
When the new object request comes then pool object will receive that request and allocate an object from the pool.
How pool object works
In pool object, We use a factory method which is used to monitor the creation of objects in pool. Whenever the new object request comes then this method will check into object pool. If this method find the object within the allot limit then it will return the object ,if not then it will create a new object.
A sample program to illustrate how to implement a pool object
using System;
using System.Collections;
namespace ObjectPoolingSampleProgram
{
class Factory
{
private static int _PoolObjectMaxSize = 4;
private static readonly Queue poolObj = new Queue(_PoolObjectMaxSize );
public User GetUser()
{
if (User .Counter >= _PoolObjectMaxSize && poolobj .Count>0)
{
objUser = RetrievePool();
}
else
{
objUser = GetNewUser();
}
return objUser ;
}
private User GetNewUser()
{
User objUsers = new User ();
poolObj .Enqueue(objUsers );
return objUsers ;
}
protected User RetrievePool()
{
User objUser;
if (poolObj .Count>0)
{
objUser= (User)poolObj.Dequeue();
User.Counter--;
}
else
{
objUser= new User();
}
return objUser;
}
}
class User
{
public static int Counter = 0;
public User()
{
++Counter;
}
private string _FirstName;
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
}
}
private void button_Click(object sender, EventArgs e)
{
Factory factoryobj = new Factory();
User myUser1 = factoryobj .GetUser();
Console.WriteLine("First Pool object");
User myUser2 = factoryobj .GetUser();
Console.WriteLine("Second Pool object");
User myUser3 = factoryobj .GetUser();
Console.WriteLine("Third Pool object")
User myUser4 = factoryobj .GetUser();
Console.WriteLine("Fourth Pool object");
}
0 Comment(s)