Back to slide -- Keyboard shortcut: 'u'  previous -- Keyboard shortcut: 'p'  next -- Keyboard shortcut: 'n'          patterns/singleton/die/singleton-die.cs - A singleton Die class.Lecture 4 - slide 25 : 29
Program 2

using System;

public class Die {
  private int numberOfEyes;
  private Random randomNumberSupplier; 
  private int maxNumberOfEyes;

  private static Die uniqueInstance = null;

  private Die (){
    randomNumberSupplier = new Random(unchecked((int)DateTime.Now.Ticks));
    this.maxNumberOfEyes = 6;
    this.Toss();
  }

  public static Die Instance(){
    if (uniqueInstance == null)
      uniqueInstance = new Die();

    return uniqueInstance;
  } 
    
  public void Toss (){
    numberOfEyes = randomNumberSupplier.Next(1,maxNumberOfEyes + 1);
  }

  public int NumberOfEyes() {
    return numberOfEyes;
  }

  public override String ToString(){
    return String.Format("Die[{0}]: {1}", maxNumberOfEyes, numberOfEyes);
  }
}