Skip to content

Instantly share code, notes, and snippets.

@poychang
Created March 2, 2021 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/4efae8dfc584df195779c7da423b1177 to your computer and use it in GitHub Desktop.
Save poychang/4efae8dfc584df195779c7da423b1177 to your computer and use it in GitHub Desktop.
[Self Instance 的寫法] 簡單的 Singleton 寫法 #dotnet #c
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