下面是一个简单的ObjectPool集合,用于我的一些类。有人能回顾一下吗?
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Mango.Collections
{
sealed class ObjectPool<T>
{
private readonly ConcurrentBag<T> _objects;
private readonly Func<T> _objectGenerator;
public ObjectPool(Func<T> objectGenerator)
{
if (objectGenerator == null) { throw new ArgumentNullException("objectGenerator"); }
_objects = new ConcurrentBag<T>();
_objectGenerator = objectGenerator;
}
public T GetObject()
{
T Item;
if (_objects.TryTake(out Item)) { return Item; }
return _objectGenerator();
}
public void PutObject(T Item)
{
_objects.Add(Item);
}
}
}发布于 2017-03-16 13:48:03
代码在我看来是干净的,但为什么要密封呢?我认为它作为其他事情的基类是有用的。它可以用抽象类来描述,也可以用GetObject<T>和PutObject<T>方法的接口来描述。
https://codereview.stackexchange.com/questions/157916
复制相似问题