C# Design Pattern: ObjectPool

juarezasjunior

Juarez Júnior

Posted on September 29, 2024

C# Design Pattern: ObjectPool

The Object Pool pattern is used to manage the reuse of expensive or time-consuming objects. Instead of creating and destroying instances repeatedly, the Object Pool maintains a pool of objects ready to be reused, which improves system efficiency, especially when creating new objects is resource-intensive. A common use of the Object Pool pattern would be in database connection management or graphical renderers.

C# Code Example:

// Example class to be managed by the Object Pool
public class Connection
{
    public string Id { get; set; }

    public Connection(string id)
    {
        Id = id;
        Console.WriteLine($"Connection {Id} created.");
    }

    public void Connect()
    {
        Console.WriteLine($"Connection {Id} connected.");
    }

    public void Disconnect()
    {
        Console.WriteLine($"Connection {Id} disconnected.");
    }
}

// Object Pool class to manage connections
public class ConnectionPool
{
    private List<Connection> _available = new List<Connection>();
    private List<Connection> _inUse = new List<Connection>();

    public Connection GetConnection()
    {
        Connection connection;

        if (_available.Count > 0)
        {
            connection = _available[0];
            _available.RemoveAt(0);
            Console.WriteLine($"Connection {connection.Id} reused.");
        }
        else
        {
            connection = new Connection(Guid.NewGuid().ToString());
        }

        _inUse.Add(connection);
        return connection;
    }

    public void ReleaseConnection(Connection connection)
    {
        _inUse.Remove(connection);
        _available.Add(connection);
        Console.WriteLine($"Connection {connection.Id} released and returned to pool.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        ConnectionPool pool = new ConnectionPool();

        // Get and use connections
        Connection connection1 = pool.GetConnection();
        connection1.Connect();

        Connection connection2 = pool.GetConnection();
        connection2.Connect();

        // Release connections back to the pool
        connection1.Disconnect();
        pool.ReleaseConnection(connection1);

        Connection connection3 = pool.GetConnection();  // Reusing released connection
        connection3.Connect();

        connection2.Disconnect();
        pool.ReleaseConnection(connection2);
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, the Connection class represents an expensive object (e.g., a database connection). The ConnectionPool manages these connections, maintaining two lists: one for available connections and another for connections in use. The GetConnection method reuses an available connection if one exists or creates a new one if needed. The ReleaseConnection method returns the connection to the pool for reuse.

Conclusion:

The Object Pool pattern is effective for managing costly resources and limiting the creation of new objects, promoting reuse. This can be essential in high-performance systems that require efficient resource management, such as database connections, threads, or memory buffers.

Source code: GitHub

💖 💪 🙅 🚩
juarezasjunior
Juarez Júnior

Posted on September 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related