well,這應該是設計模式裡面最簡單的一種模式。
邏輯上來說,建一個class基本上都是為了可以new很多物件出來, 但是有些時候,有些物件你需要跨method使用,所以你就讓它變成一個全域變數,
問題在於,你並不希望說她一開始就被分配空間,希望她是在用到的時候才被產生出來, 而且你希望當我呼叫這個物件的時候,基本上它是能呼叫到同一個物件。 獨體模式可以解決這個問題。
與其中文解釋不如看程式碼比較好了解的一種模式。 XD
//定義類別 using System; using System.Collections.Generic; using System.Linq; using System.Text;
namespace ConsoleApplication2 { class Program {
static void Main(string[] args) { Single testSingle = Single.Init(); testSingle.strName = "Hello!I’am the only One!"; Console.WriteLine("In Main function:"); Console.WriteLine(" {0}", testSingle.strName); Console.WriteLine("Call method ;DoSomething():"); DoSomething(); Console.ReadKey(); }
static private void DoSomething() { Single testSingle = Single.Init(); Console.WriteLine(" {0}", testSingle.strName); } }
//定義類別 public class Single { private static Single _Single; //建立一個物件 public string strName="";
public static Single Init() { if (_Single == null) _Single = new Single();
return _Single; }
private Single() //不允許外部存取的建構式 { }
} }
//程式碼2012/8/27更新。
不過其實讀到這邊的時候,第一個念頭就是, Object-C的 init 的method 一開始就是在用這種模式,目前手上幾本教學的書, 很自然的就把獨體模式視為"應該做的事情",相較之下,不知道是我書選得不好還是怎麼樣,似乎C#的書比較少著墨於這端。 o_oa
如有誤謬,歡迎指導。 囧
沒有留言 :
張貼留言