using System.Collections.Concurrent;
private static readonly ObjectPool<NotifyCache> cache = new ObjectPool<NotifyCache>(() => new NotifyCache());
private NotifyCache() { }
public static Action<IAccelerometerListener> Create(int x, int y, int z)
private void Call(IAccelerometerListener listener)
listener.OnAccelerometersChanged(x, y, z);
public static void Main()
Test.Notify(NotifyCache.Create(3, 5, 6));
Test.Notify(NotifyCache.Create(13, 5, 16));
Test.Notify(NotifyCache.Create(3, 25, 6));
Test.Notify(NotifyCache.Create(3, 15, 6));
Test.Notify(NotifyCache.Create(13, 5, 6));
public interface IAccelerometerListener
void OnAccelerometersChanged(int x, int y , int z);
private class Test : IAccelerometerListener
public void OnAccelerometersChanged(int x, int y, int z)
Console.WriteLine($"x :{x}, y: {y}, z {z}");
public static void Notify(Action<IAccelerometerListener> action)
public class ObjectPool<T>
private readonly ConcurrentBag<T> _objects;
private readonly Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator)
_objectGenerator = objectGenerator ?? throw new ArgumentNullException(nameof(objectGenerator));
_objects = new ConcurrentBag<T>();
public T Get() => _objects.TryTake(out T item) ? item : _objectGenerator();
public void Return(T item) => _objects.Add(item);