Mic*_*ael 7 c# caching responsibility
我正在研究允许用户通过实现一组接口来扩展系统的软件.
为了测试我们正在做的事情的可行性,我的公司通过在用户完全相同的方式中实现这些类中的所有业务逻辑来" 吃掉自己的狗食 ".
我们有一些实用程序类/方法将所有内容绑定在一起并使用可扩展类中定义的逻辑.
我想缓存用户定义函数的结果.我应该在哪里这样做?
是班级本身吗?这似乎可能会导致很多代码重复.
它是使用这些类的实用程序/引擎吗?如果是这样,不知情的用户可以直接调用类函数,而不是获得任何缓存优势.
public interface ILetter { string[] GetAnimalsThatStartWithMe(); }
public class A : ILetter { public string[] GetAnimalsThatStartWithMe()
{
return new [] { "Aardvark", "Ant" };
}
}
public class B : ILetter { public string[] GetAnimalsThatStartWithMe()
{
return new [] { "Baboon", "Banshee" };
}
}
/* ...Left to user to define... */
public class Z : ILetter { public string[] GetAnimalsThatStartWithMe()
{
return new [] { "Zebra" };
}
}
public static class LetterUtility
{
public static string[] GetAnimalsThatStartWithLetter(char letter)
{
if(letter == 'A') return (new A()).GetAnimalsThatStartWithMe();
if(letter == 'B') return (new B()).GetAnimalsThatStartWithMe();
/* ... */
if(letter == 'Z') return (new Z()).GetAnimalsThatStartWithMe();
throw new ApplicationException("Letter " + letter + " not found");
}
}
Run Code Online (Sandbox Code Playgroud)
应该LetterUtility负责缓存?应该是ILetter的每个实例吗?是否有其他完全可以做到的事情?
我试图保持这个例子简短,所以这些示例函数不需要缓存.但是考虑一下我添加这个(new C()).GetAnimalsThatStartWithMe()
每次运行需要10秒钟的类:
public class C : ILetter
{
public string[] GetAnimalsThatStartWithMe()
{
Thread.Sleep(10000);
return new [] { "Cat", "Capybara", "Clam" };
}
}
Run Code Online (Sandbox Code Playgroud)
我发现自己在尽可能快地制作我们的软件和维护更少的代码(在这个例子中:缓存结果LetterUtility
)和反复完成相同的工作(在这个例子中:每次C
使用等待10秒)之间进行斗争.
Eri*_*ert 10
哪个层最适合缓存这些用户可定义函数的结果?
答案非常明显:能够正确实现所需缓存策略的层是正确的层.
正确的缓存策略需要具有两个特征:
它绝不能提供过时的数据; 它必须知道被缓存的方法是否会产生不同的结果,并且在调用者获得陈旧数据之前的某个时刻使缓存无效
它必须代表用户有效地管理缓存资源.没有过期策略的缓存没有边界增长有另一个名称:我们通常称它们为"内存泄漏".
系统中哪些层知道问题的答案"缓存陈旧?" 并且"缓存太大了吗?" 那是应该实现缓存的层.
虽然我不懂C#,但这似乎是使用AOP(面向方面编程)的情况。这个想法是,您可以“注入”要在执行堆栈中的某些点执行的代码。
您可以添加缓存代码,如下所示:
IF( InCache( object, method, method_arguments ) )
RETURN Cache(object, method, method_arguments);
ELSE
ExecuteMethod(); StoreResultsInCache();
Run Code Online (Sandbox Code Playgroud)
然后,您定义应该在每次调用接口函数(以及实现这些函数的所有子类)之前执行此代码。
一些 .NET 专家可以告诉我们如何在 .NET 中做到这一点吗?
归档时间: |
|
查看次数: |
975 次 |
最近记录: |