我将以帖子的长度道歉来开始这个问题.所以我节省了一些时间,我的问题是,我被困在脑子里的班级模式显然是有缺陷的,我看不出一个好的解决方案. 在我正在开发的项目中,我需要在一块
在我正在开发的项目中,我需要在一块数据上使用操作算法,我们称之为DataCache.有时这些算法会返回自身需要缓存的结果,因此我设计了一个方案.
我有一个算法基类,看起来像这样
abstract class Algorithm<T>
{
protected abstract T ExecuteAlgorithmLogic(DataCache dataCache);
private readonly Dictionary<DataCache, WeakReference> _resultsWeak = new Dictionary<DataCache, WeakReference>();
private readonly Dictionary<DataCache, T> _resultsStrong = new Dictionary<DataCache, T>();
public T ComputeResult(DataCache dataCache, bool save = false)
{
if (_resultsStrong.ContainsKey(dataCache))
return _resultsStrong[dataCache];
if (_resultsWeak.ContainsKey(dataCache))
{
var temp = _resultsWeak[dataCache].Target;
if (temp != null) return (T) temp;
}
var result = ExecuteAlgorithmLogic(dataCache);
_resultsWeak[dataCache] = new WeakReference(result, true);
if (save) _resultsStrong[dataCache] = result;
return result;
}
}
如果调用ComputeResult()并提供DataCache,则可以选择缓存结果.此外,如果您幸运的话,如果GC还没有收集它,那么结果仍然存在.每个DataCache的大小都是几百兆字节,在你问之前每个大约有10个数组,它们包含基本类型,如int和float.
我的想法是,实际的算法看起来像这样:
class ActualAgorithm : Algorithm<SomeType>
{
protected override SomeType ExecuteAlgorithmLogic(DataCache dataCache)
{
//Elves be here
}
}
我会定义几十个.cs文件,每个文件用于一个算法.这种方法存在两个问题.首先,为了使其工作,我需要实例化我的算法并保留该实例(或者结果不被缓存而整个点都是静音的).但后来我在每个派生类中都得到了一个难看的单例模式实现.它看起来像这样:
class ActualAgorithm : Algorithm<SomeType>
{
protected override SomeType ExecuteAlgorithmLogic(DataCache dataCache)
{
//Elves and dragons be here
}
protected ActualAgorithm(){ }
private static ActualAgorithm _instance;
public static ActualAgorithm Instance
{
get
{
_instance = _instance ?? new ActualAgorithm();
return _instance;
}
}
}
因此,在每个实现中,我将不得不复制单例模式的代码.其次,数十个CS文件听起来有点矫枉过正,因为我真正想要的只是一个函数返回一些可以为各种DataCache对象缓存的结果.当然,必须有一个更聪明的方法来做到这一点,我非常感谢在正确的方向上轻推.
我的评论意思是这样的:abstract class BaseClass<K,T> where T : BaseClass<K,T>, new()
{
private static T _instance;
public static T Instance
{
get
{
_instance = _instance ?? new T();
return _instance;
}
}
}
class ActualClass : BaseClass<int, ActualClass>
{
public ActualClass() {}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ActualClass.Instance.GetType().ToString());
Console.ReadLine();
}
}
这里唯一的问题是你将拥有一个公共构造函数.
