============1單例模式==============性能
using System;測試
using System.Collections.Generic;spa
using System.Linq;orm
using System.Text;對象
using System.Threading;string
namespace ConsoleApplication13it
{io
class Programclass
{sed
static void Main(string[] args)
{
for (int i = 0; i < 1000; i++)
{
Thread t = new Thread(new ThreadStart(() =>
{
Singleton s = Singleton.GetInstance();
}));
t.Start();
}
Console.WriteLine("ok");
Console.ReadKey();
}
}
public class Singleton
{
private Singleton()
{
//只要輸出一次.就證實建立了一個對象。
Console.WriteLine(" . ");
}
private static Singleton _instance;
private static readonly object _syn = new object();
public static Singleton GetInstance()
{
//每次都鎖定下降性能,因此只有爲空值時才鎖定。
if (_instance == null)
{
lock (_syn)
{
//爲了防止在第一次判斷_instance==null後,在鎖定以前_instance又被賦值,因此鎖定以後必定要再判斷一次是否已經建立了對象。
if (_instance == null)
{
_instance = new Singleton();
}
}
}
return _instance;
}
}
}
=============================2單例模式(另外一種寫法)==========================
public sealed class Singleton2
{
private Singleton2()
{
Console.WriteLine(".");
}
//靜態成員初始化,只在第一次使用的時候初始化一次。
private static readonly Singleton2 _instance = new Singleton2();
public static Singleton2 GetInstance()
{
return _instance;
}
}
=================測試====================
for (int i = 0; i < 1000; i++)
{
Thread t = new Thread(new ThreadStart(() =>
{
Singleton2 s = Singleton2.GetInstance();
}));
t.Start();
}
Console.WriteLine("ok");
Console.ReadKey();
//======================實現窗口類(Form)的單例模式===============
public partial class Form2 : Form
{
private Form2()
{
InitializeComponent();
}
private static Form2 f2;
private static readonly object syn = new object();
public static Form2 GetForm2()
{
if (f2 == null || f2.IsDisposed)
{
lock (syn)
{
if (f2 == null || f2.IsDisposed)
{
f2 = new Form2();
}
}
}
return f2;
}
}