64 lines
1.5 KiB
C#
64 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
|
|
namespace Maki
|
|
{
|
|
internal abstract class BaseManager<T> : IDisposable
|
|
{
|
|
protected readonly HashSet<T> Collection = new HashSet<T>();
|
|
public IEnumerable<T> Items => Collection;
|
|
public int Count => Collection.Count;
|
|
|
|
public event Action<T> OnAdd;
|
|
public event Action<T> OnRemove;
|
|
|
|
protected virtual bool DisposeOnRemove => true;
|
|
|
|
protected bool IsDisposed = false;
|
|
|
|
~BaseManager()
|
|
=> Dispose(false);
|
|
|
|
public void Dispose()
|
|
=> Dispose(true);
|
|
|
|
protected void Dispose(bool disposing)
|
|
{
|
|
if (IsDisposed)
|
|
return;
|
|
|
|
IsDisposed = true;
|
|
Collection.ToList().ForEach(x => Remove(x));
|
|
Collection.Clear();
|
|
|
|
if (disposing)
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
public virtual void Add(T item)
|
|
{
|
|
if (item == null)
|
|
return;
|
|
|
|
lock (Collection)
|
|
Collection.Add(item);
|
|
|
|
OnAdd?.Invoke(item);
|
|
}
|
|
|
|
public virtual void Remove(T item)
|
|
{
|
|
if (item == null)
|
|
return;
|
|
|
|
lock (Collection)
|
|
Collection.Remove(item);
|
|
|
|
OnRemove?.Invoke(item);
|
|
|
|
if (DisposeOnRemove && item is IDisposable)
|
|
(item as IDisposable).Dispose();
|
|
}
|
|
}
|
|
}
|