Advertisement
ivandrofly

Static Classes vs Singleton Design

Feb 1st, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.35 KB | None | 0 0
  1. using System.IO;
  2. namespace Static_s_Roots
  3. {
  4.     class Logger
  5.     {
  6.         StreamWriter outStream;
  7.         int logNumber = 0;
  8.         static Logger theInstance = new Logger();
  9.  
  10.         //Note the constructor has to be private / you can also make this class sealed
  11.         Logger() { }
  12.  
  13.         public void initializeLogging()
  14.         {
  15.             outStream = new StreamWriter("mylog.txt");
  16.         }
  17.         public void shutDownLoggin()
  18.         {
  19.             outStream.Close();
  20.         }
  21.         public void logMessage(string message)
  22.         {
  23.             outStream.WriteLine((logNumber++) + ": " + message);
  24.         }
  25.  
  26.         public static Logger TheInstance
  27.         {
  28.             get
  29.             {
  30.                 if (theInstance == null)
  31.                     theInstance = new Logger();
  32.                 return theInstance;
  33.             }
  34.         }
  35.     }
  36.     class Program
  37.     {
  38.         static void Main(string[] args)
  39.         {
  40.             Logger.TheInstance.initializeLogging();
  41.             Logger.TheInstance.logMessage("I love static data");
  42.             Logger.TheInstance.logMessage("static data exists before and after main()");
  43.             Logger.TheInstance.logMessage("When I think static, I think memory that created by the compiler");
  44.             Logger.TheInstance.shutDownLoggin();
  45.         }
  46.     }
  47. }
  48. // By: Jamie King
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement