Erhan 8/7/2016 0

Singleton Pattern

You are working on an application which requires Logging information into a file
named Application.Log. The logging is managed by a class named LogManager . The
LogManager through its constructor keeps a lock on the File.
The LogManager instance an be created throughout the application and it will result
in Exceptions. Above that there is only instance requirement for the LogManager
The above problem can be solved using Singleton Pattern.
GoF Definition: "Ensure a class only has one instance, and provide a global point of
access to it"
To implement the specification above we have to perform the following:
. Make the Constructor Private and Create only 1 Instance
. Create a Static Property to Access the Instance
Following is the modified class definition according to Singleton Pattern.

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

namespace SingletonPattern
    public class LogManager
        private static LogManager _instance;

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

                return _instance;

        public LogManager()
            _fileStream = File.OpenWrite(GetExecutionFolder()   "\\Application.log" );
            _streamWriter = new StreamWriter (_fileStream);

        private FileStream _fileStream;
        private StreamWriter _streamWriter;

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


        public string GetExecutionFolder()
            return Path.GetDirectoryName(System.Reflection.Assembly .GetExecutingAssembly().Location);

Report Bug

Please Login to Report Bug

Reported Bugs


Please Login to Comment