Advertisement
csaki

Simple singleton pattern

Feb 13th, 2014
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.09 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace singleton
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             Singleton s1 = Singleton.GetInstance();
  13.             Singleton s2 = Singleton.GetInstance();
  14.             Console.WriteLine(s2.ToString());
  15.             Console.WriteLine(s1.ToString());
  16.             Console.ReadLine();
  17.         }
  18.     }
  19.  
  20.     // NOT THREADSAFE and it is LAZY
  21.     class Singleton
  22.     {
  23.         static Singleton instance;
  24.  
  25.         // single, STATIC entry point
  26.         public static Singleton GetInstance()
  27.         {
  28.             if (instance == null)
  29.                 instance = new Singleton();
  30.             return instance;
  31.         }
  32.  
  33.         int _test;
  34.         public int test
  35.         {
  36.             get { return _test; }
  37.             set { _test = value; }
  38.         }
  39.  
  40.         private Singleton()
  41.         {
  42.             test = new Random().Next(1000);
  43.         }
  44.  
  45.         public override string ToString()
  46.         {
  47.             return test.ToString();
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement