TODO…
單例模式(Singleton)
定義:只有一個實例,而且自行實例化並向整個系統提供這個實例。
屬於創建模式,
這個模式涉及到一個單一的類別,他必須要創建自己的實例,
並且確保只有單一個對象被創建。
這個類別提供一個方法訪問其被創建的唯一一個對象。
https://hackmd.io/@Daniel-Handsome/r1Z7KLzlK
存取IO和資料庫等資源,這時候要考慮使用單例模式。
設計模式
1
2
3
4
5
6
7
8
9
class Test {
private Test() { }
private static Test instance = new Test();
public static Test GetInstance() {
return instance;
}
//TODO:信息 屬性
}
Test.GetInstance().xxx;
回顧
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//非靜態類,但全局只有一個對象/物件
class Test {
//1.「構造函式」設為 private
private Test() { }
//2.然後提供一個private然後static類型的Test,並new一個Test給他
private static Test instance = new Test();
//3.因為外界訪問不到instance,所以加一個public static的方法返回一個Test對象/物件
public static Test GetInstance() {
return instance;
}
//TODO: 信息、屬性
}
//怎麼進行使用呢?
Test.GetInstance().xxx;
1.「構造函式」設為 private
這樣外界就沒有辦法去
new它了
2.然後提供一個private然後static類型的Test,名為instance,然後new一個Test給他
因為我是在類別內
new它,所以說,我可以調用這樣的一個無參構造方法。
雖然它是全局static的,但是他是private,所以外界是訪問不到它的
3.因為外界訪問不到instance,所以加一個public static的方法,返回一個Test對象/物件
練習
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Test {
private Test() { }
private static Test instance = new Test();
public static Test GetInstance() {
return instance;
}
public int Id { get; set; }
public string Name { get; set; }
public void SayHello() {
Console.WriteLine($"Hi {Name}");
}
}
internal class Program
{
static void Main(string[] args)
{
Test.GetInstance().Id = 123;
Test.GetInstance().Name = "Rii";
Test.GetInstance().SayHello();
}
}
