DEV Community

Devstoc
Devstoc

Posted on

Pooling Design Pattern using C#

The pooling pattern is a software design pattern that is used to manage the creation and reuse of objects, often in situations where creating new objects is expensive or time-consuming. The basic idea behind the pattern is to create a pool of objects that can be reused, rather than creating new objects each time they are needed.

Pooling Design Pattern - Devstoc

Implementation

To implement the pooling pattern in C#, you will need to create a pool class that manages the creation and reuse of objects. Here is an example implementation of a pool class that can be used to manage the creation and reuse of objects of type T:

class ObjectPool<T>
{
    private readonly Stack _pool;
    private readonly Func _objectGenerator;

    public ObjectPool(Func objectGenerator)
    {
        _pool = new Stack();
        _objectGenerator = objectGenerator;
    }

    public T GetObject()
    {
        if (_pool.Count > 0)
        {
            return _pool.Pop();
        }
        return _objectGenerator();
    }

    public void PutObject(T obj)
    {
        _pool.Push(obj);
    }
}
Enter fullscreen mode Exit fullscreen mode

The ObjectPool class uses a Stack to store the available objects, and a Func to create new objects when none are available in the pool. The GetObject method is used to retrieve an object from the pool, either by returning an existing object or by creating a new one using the _objectGenerator function. The PutObject method is used to return an object to the pool.
Check out my article to view real-time examples

Top comments (0)