Skip to content

Instantly share code, notes, and snippets.

@IamLizu
Last active September 29, 2019 18:41
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 IamLizu/628dfb7103cb970a09bdc60ae39e756f to your computer and use it in GitHub Desktop.
Save IamLizu/628dfb7103cb970a09bdc60ae39e756f to your computer and use it in GitHub Desktop.
using System;
namespace OOP.Singleton
{
class Singleton
{
// holds the singleton instance
private static Singleton Instance;
public string text;
// private constructor so that Singleton class itself can call itself.
private Singleton (string text)
{
this.text = text;
}
public static Singleton GetInstance(string text)
{
// checks if instance is created
if (Instance == null)
{
// if note create one
Instance = new Singleton(text);
}
// return the created instance on every subsequent call
return Instance;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Demonstrates Singleton class. Output of the two print statement bellow will be same");
Console.WriteLine("because the class returned the cached instance of the second call.");
Singleton one = Singleton.GetInstance("One");
Singleton two = Singleton.GetInstance("Two");
Console.WriteLine(one.text);
Console.WriteLine(two.text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment