singleton模式可以保證這個類只有一個執行個體。
下面是這個模式的一種典型的寫法
public class Singleton
{
protected Singleton() { }
private static Singleton instance;
private static object objLock = new object();
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (objLock)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
為了保證多線程環境下也只能有一個執行個體,所以在這裡使用了鎖(lock).如果每次擷取的時候,都要將lock一次,這會對效能產生影響,所以在lock之前,我們又進行了一次判斷。一般情況下,同一個運用程式都是使用同一個配置。所以配置就是一個Singleton的運用了。
public class Settings
{
private Settings() { }
private decimal _Tax = 0;
public decimal Tax
{
get { return _Tax; }
set { _Tax = value; }
}
private decimal _Discount = 0;
public decimal DefaultDiscount
{
get { return _Discount; }
set { _Discount = value; }
}
private void LoadSettings()
{
SettingsProvider.Load(this);
}
private static Settings instance = null;
private static object lockObj = new object();
public static Settings CurrentSettings
{
get
{
if (instance == null)
{
lock (lockObj)
{
if (instance == null)
{
instance = new Settings();
instance.LoadSettings();
}
}
}
return instance;
}
}
}
有些人習慣把配置寫在資料庫中,然後每次都讀取一次資料庫中的資訊。在多使用者環境下,或者類似WebForm運用程式,這樣做浪費了一次資料庫連接。而且不能保證修改後的資料馬上被運用。有些商務邏輯需要使用單例模式。在我開發的一個餐廳管理軟體中,當前的上下文中只能為一個客戶點菜。這個時候就需要使用單例模式了,而且使用了單例模式後,在別的類中就可以很放心的使用這個類的執行個體,降低了開發的難度。
private void Bind()
{
this.Reset();
if (currentButton != null)
currentButton.BackColor = currentButton.Parent.BackColor;
Dish currentDish = Context.CurrentContext.CurrentDish;
bool verdict = (currentDish != null);
List<Dish> lst = Paging.GetList(Context.CurrentContext.DishList, pageIndex, pageSize);
for (int i = 0; i < dishButtons.Length && i < lst.Count; i++)
{
dishButtons[i].OrderDish = lst[i];
if (verdict && currentDish.Equals(lst[i]))
{
currentButton = dishButtons[i];
currentButton.BackColor = Color.SkyBlue;
}
}
this.Refresh();
}