Simple Singleton pattern in C#
Singleton Pattern C#
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
public class Singleton{ | |
private volatile static Singleton uniqueInstance; | |
private static readonly object padlock = new object(); | |
public int sample = 10; | |
private Singleton(){ | |
Console.WriteLine("Create new instance here"); | |
} | |
public static Singleton getInstance(){ | |
if (uniqueInstance == null){ | |
lock (padlock){ | |
if (uniqueInstance == null){ | |
Console.WriteLine("Create new instance"); | |
uniqueInstance = new Singleton(); | |
} | |
} | |
} | |
return uniqueInstance; | |
} | |
public void setSample(int i) { | |
this.sample = i | |
} |
コメント
コメントを投稿