常规接口:Decorator模式和泛型
public interface IComputation
{
void Reset();
float GetValue1();
float GetValue2();
}
通用接口:
public interface IComputation<T> : IComputation where T : IComputation
{
T Proxy { get; set; }
}
现在的类:
public abstract class Computation<T> : IComputation<T> where T : IComputation
{
public T Proxy { get; set; }
}
班 'ComputationCache' 是“装饰”的计算:
internal abstract class ComputationCache<T> : IComputation where T : IComputation
{
public T Proxy { get; set; }
public float GetValue1()
{
bool isCached = //check cache.
if(!isCached)
{
//compute value
float value1 = Proxy.GetValue1();
//update cache
return value;
}
}
}
要初始化装饰计算,我试过如下:
public ComputationCache(IComputation<T> proxy)
{
Proxy = (T) proxy;
proxy.Proxy = this;
}
...它提供了以下错误“:
Cannot convert source type 'ComputationCache' to target type 'T'.
可以在它是否是更好有人评论使用方法:
ComputationCache<T> : IComputation where T : IComputation
VS
ComputationCache<T> : IComputation<T> where T : IComputation
你的抽象看起来有点过分 – Rahul
我必须说,你失去了我 –
@Rahul。上面显示的类是抽象的,并且被多个Computation的子类进行分类,以及从基类缓存类派生的相应的“ComputationCache”。我试图避免在下层重复投射'Proxy'属性 – alhazen