Design Patterns - Singleton Pattern

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DesignPattern_Singleton
{
   class Program
   {
      static void Main(string[] args)
      {
         /* The program will first check if there is an instance of LogManager
         * if there is one, then it will continue to use the instance
         * else it will create a new instance and call the private method 
         * "LogManager"
         * private "LogManager" method will create one text file 
         * with a unique name
         * and "WriteLog" will write the log message to the file 
         * which was created by the LogManager
         */
         LogManager.Instance.WriteLog("SINGLETON PATTERN TEST MESSAGE");
      }
   }

   public class LogManager
   {
      private static LogManager instance;
      private FileStream fileStream;
      private StreamWriter streamWriter;

      public static LogManager Instance
      {
         get
         {
            if (instance == null)
            instance = new LogManager();

            return instance;
         }
      }

      private LogManager()
      {
         string fileName = Environment.CurrentDirectory + "\\ApplicationLog_" + Guid.NewGuid() + ".txt";
         fileStream = File.OpenWrite(fileName);

         streamWriter = new StreamWriter(fileStream);
      }

      public void WriteLog(string logMessage)
      {
         StringBuilder message = new StringBuilder();
         message.AppendLine("Date: " + DateTime.Now.ToString()+" -- Message: "+logMessage);

         streamWriter.WriteLine(message.ToString());
         streamWriter.Flush();
      }
   }
}


Comments

Popular posts from this blog

Umbraco Notifications - Save and Send For Approval Process

Fix for "Websites cannot be started unless both the Windows Activation Service (WAS) and the World Wide Web Publishing Service (W3SVC) are running, Both services are currently stopped"

How to specify proxy credentials in web.config