Reuses expensive-to-create objects instead of creating and destroying them repeatedly.
Common for database connections, thread pools, etc.
class Connection {
void query(String sql) => print('Executing: $sql');
}
class ConnectionPool {
final List<Connection> _available = [];
final int _maxSize;
ConnectionPool(this._maxSize);
Connection acquire() {
if (_available.isNotEmpty) return _available.removeLast();
return Connection(); // create new if pool isn't full
}
void release(Connection conn) {
if (_available.length < _maxSize) _available.add(conn);
}
}
// Usage
final pool = ConnectionPool(5);
final conn = pool.acquire();
conn.query('SELECT * FROM users');
pool.release(conn);