[英]How to create a singleton pattern of the following class
我有一個創建對象上下文的類。 要管理對象創建,我想使用單例模式。 如何在C#中將以下類對象創建模式創建為單例?
public abstract class EFContextBase<TContext> : IDisposable where TContext : ObjectContext, new()
{
private TContext _dataContext;
protected virtual TContext DataContext
{
get
{
if ((object)this._dataContext == null)
this._dataContext = Activator.CreateInstance<TContext>();
return this._dataContext;
}
}
public EFContextBase()
{
this.DataContext.ContextOptions.LazyLoadingEnabled = true;
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize((object)this);
}
private void Dispose(bool disposing)
{
if (!disposing || (object)this._dataContext == null)
return;
this._dataContext.Dispose();
this._dataContext = default(TContext);
}
}
為什么要制作一個抽象類Singleton? 制作了抽象類,以供其他類繼承。 Singleton是一種設計模式,用於避免使用靜態方法並保留使您的類可實例化的可能性(也許供以后使用)。 您應該考慮一下您的體系結構。
通常,您應通過以下方式制作類單例:
private static readonly <<YourClass>> singleton = new <<YourClass>>()
public <<YourClass>> Singleton
{
get { return singleton; }
}
有以下幾種經典的單例實現:
不要冒險,從最了解的人那里獲取它: http : //csharpindepth.com/articles/general/singleton.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.