using System;
namespace DesignPattern.Singleton
{
class Program
{
var printer1 = Printer.GetInstance();
var printer2 = Printer.GetInstance();
Console.WriteLine(printer1.GetHashCode()); //output 20538874
Console.WriteLine(printer2.GetHashCode()); //output 20538874
//both printer1 and printer2 has the same hash code
//that is the same instance
}
public class Printer
{
private static Printer instance;
private Printer(){}
public static Printer GetInstance()
{
if (instance == null)
{
instance = new Printer();
}
return instance;
}
}
}public class SingletonOnDemand {
private SingletonOnDemand () {}
private static class Singleton {
private static final SingletonOnDemand instance = new SingletonOnDemand();
}
public static SingletonOnDemand getInstance () {
System.out.println("create instance");
return Singleton.instance;
}
}