DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

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

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video →

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay