Skip to content

Instantly share code, notes, and snippets.

@gucu112
Last active February 21, 2020 20:59
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 gucu112/ec1abf5f07d37afa95b9b2966f7ad513 to your computer and use it in GitHub Desktop.
Save gucu112/ec1abf5f07d37afa95b9b2966f7ad513 to your computer and use it in GitHub Desktop.
C# Singleton Pattern
namespace Gucu112.SingletonPattern
{
class Singleton : IDisposable
{
private static Lazy<Singleton> instance
= new Lazy<Singleton>(() => new Singleton());
private Singleton()
{
// Singleton initialized
}
public static Singleton Instance => instance.Value;
public void Dispose()
{
if (instance.IsValueCreated)
{
// Singleton disposed
instance = new Lazy<Singleton>(() => new Singleton());
}
}
}
}
<Query Kind="Program" />
void Main()
{
"Calling singleton dispose".Dump();
Singleton.Instance.Dispose();
"Calling singleton instance in using clause".Dump();
using (var singleton = Singleton.Instance)
{
"Using singleton instance".Dump();
}
"Calling singleton instance".Dump();
var test = Singleton.Instance;
"Calling singleton dispose".Dump();
Singleton.Instance.Dispose();
"Calling singleton dispose".Dump();
Singleton.Instance.Dispose();
}
public class Singleton : IDisposable
{
private static Lazy<Singleton> instance
= new Lazy<Singleton>(() => new Singleton());
private Singleton()
{
"Singleton initialized".Dump();
}
public static Singleton Instance => instance.Value;
public void Dispose()
{
if (instance.IsValueCreated)
{
"Singleton disposed".Dump();
instance = new Lazy<Singleton>(() => new Singleton());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment