using System.Collections.Generic;
using System.Linq;
namespace Chernobyl.DesignPatterns.Pool
{
///
/// A class that represents a simple pool or a
/// pool that just holds a set of objects that
/// can be taken and returned.
///
/// The type of item to pool together.
public class SimplePool : IPool
{
///
/// Constructor that creates a SimplePool which holds
/// objects in a LinkedList.
///
public SimplePool() : this(new LinkedList())
{
}
///
/// Constructor.
///
/// The collection to use to hold objects in the pool.
public SimplePool(ICollection collection)
{
PooledObjects = collection;
}
///
/// Takes an object from the pool. If the pool has
/// no more objects to give or it does not want to
/// give an object out then null will be returned.
///
/// The object to fill with
/// the taken object.
/// True if there was an object that could be
/// taken from the pool and that object was assigned to
/// , false if otherwise.
public bool Take(out PooledType objectToTake)
{
if (PooledObjects.Count == 0)
{
objectToTake = default(PooledType);
return false;
}
objectToTake = PooledObjects.First();
PooledObjects.Remove(objectToTake);
return true;
}
///
/// Returns a previously taken object to the pool.
///
/// The object to return
/// to the pool.
public void Return(PooledType objectToReturn)
{
PooledObjects.Add(objectToReturn);
}
///
/// Adds an item to the collection of pooled objects.
///
/// The item to add.
public void Add(PooledType item)
{
PooledObjects.Add(item);
}
///
/// Clears out the collection of pooled objects
///
public void Clear()
{
PooledObjects.Clear();
}
///
/// The number of objects contained by the collection of pooled objects.
///
public int Count
{
get { return PooledObjects.Count; }
}
///
/// Removes an item from the collection of pooled objects.
///
/// The item to remove.
/// True if the item was removed, false
/// if otherwise.
public bool Remove(PooledType item)
{
return PooledObjects.Remove(item);
}
///
/// The list of pooled objects.
///
public ICollection PooledObjects { get; protected set; }
}
}