想象一下,我有一個用於顯示文本的多個Viewer組件,並且它們有幾個用戶可以切換的模式(用於查看文本/二進制/十六進制的不同字體預設)。 什麼是管理共享對象的最佳方法 - 例如字體,查找對話框等?我認爲帶有懶惰初始化對象的靜態類是可以的,但這可能是錯誤的想法。在類之間管理共享資源?
static class ViewerStatic
{
private static Font monospaceFont;
public static Font MonospaceFont
{
get
{
if (monospaceFont == null)
//TODO read font settings from configuration
monospaceFont = new Font(FontFamily.GenericMonospace, 9, FontStyle.Bold);
return monospaceFont;
}
}
private static Font sansFont;
public static Font SansFont
{
get
{
if (sansFont == null)
//TODO read font settings from configuration
sansFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold);
return sansFont;
}
}
}
請注意,您放入的任何IDisposable資源(字體,對話框等)你的靜態類將被分配給你的應用程序的生命。這可能是你想要的;只是供參考。 – TrueWill 2010-03-23 17:08:09
這就是我想要的,因爲我希望資源能夠在創建後永久生存,因此可以在第一次延遲加載之後「立即」提升它們。 – Axarydax 2010-03-23 17:16:12
如果我在同行評議中閱讀這段代碼,我不會眨眼睛(看起來不錯!)。 – 2010-03-23 19:41:25