網誌分類:程式編寫 |
Singleton 原意
Ensure a class has only one instance and provide a global point of access to it.
Singleton: 比如印表機,你只能有一個Spooler,從以避免兩個列印動作同時輸入至印表機中(總不可能同一時間列印兩張紙出來吧);如一些資料庫的管理,都需要一個CONNECTION OBJECT,其他FUNCTION都可以透過這個CONNECTION OBJECT來連接資料庫;
一個以前上學時的簡單例子:
using System;
namespace Singleton
{
class MainApp
{
static void Main()
{
// Constructor is protected -- cannot use new
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
if (s1 == s2)
{
Console.WriteLine("Objects are the same instance");
}
// Wait for user
Console.Read();
}
}
// "Singleton"
class Singleton
{
private static Singleton instance;
// Note: Constructor is 'protected'
看到這該大致明白什麼叫作SINGLETON...簡單一點說你正在看書時再也看電視吧...
總要分心一下...才能做到...
SINGLETON就是要你完成專心一個工作後再接受作下一個工作。(希望大家明白吧)

