Created
March 2, 2021 01:17
-
-
Save poychang/4efae8dfc584df195779c7da423b1177 to your computer and use it in GitHub Desktop.
[Self Instance 的寫法] 簡單的 Singleton 寫法 #dotnet #c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
var instance1 = SampleService.Instance; | |
var instance2 = SampleService.Instance; | |
Console.WriteLine(instance1.WhoAmI().Equals(instance2.WhoAmI()) ? "It's the same instance." : "It's NOT the same instance."); | |
Console.WriteLine(); | |
var instanceWithCtor1 = SampleServiceWithCtor.SelfInstance("Poy Chang"); | |
var instanceWithCtor2 = SampleServiceWithCtor.SelfInstance("Poy Chang"); | |
Console.WriteLine(instanceWithCtor1.WhoAmI().Equals(instanceWithCtor2.WhoAmI()) ? "It's the same instance." : "It's NOT the same instance."); | |
} | |
public class SampleService | |
{ | |
private static SampleService instance; | |
public static SampleService Instance | |
{ | |
get { return instance ?? (instance = new SampleService()); } | |
set { instance = value; } | |
} | |
public int WhoAmI() | |
{ | |
Console.WriteLine(instance.GetHashCode()); | |
return instance.GetHashCode(); | |
} | |
} | |
// 若建構式需要參數可以這樣做 | |
public class SampleServiceWithCtor | |
{ | |
private static SampleServiceWithCtor instance; | |
private string Name; | |
public SampleServiceWithCtor(string name) | |
{ | |
Name = name; | |
} | |
public static SampleServiceWithCtor SelfInstance(string name = null) | |
{ | |
return instance ?? (instance = new SampleServiceWithCtor(name)); | |
} | |
public int WhoAmI() | |
{ | |
Console.WriteLine($"{instance.GetHashCode()}, {Name}"); | |
return instance.GetHashCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment