Singleton Implementation


Here is a fundamental illustration of log mechanism using singleton pattern. Singleton is a creational type of pattern. I’ve already attached an UML diagram which i copied from oodesign[dot]com website.

Some outlines;
Thread-safe implementation: Our example is thread safe . Be carrefull about multithreading.
Lazy instantiation: Instance will be created when we call named “instance” property. This ensures that the instance will be created on demand.
Early instantiation: logger object instantiated when the class is loaded and not when it is first used.
Double Check of instance: If we do not check instance before lock it causes performance problems on the flying applications. We need to check Instance is null and then lock the object. This is the to workaround performance problems.

You can use this example just like this;

Logger.Instance.Write(exc.Message);

logger class’ımız aşağıdaki gibi;

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

namespace DesignPatternTermProject.Singleton
{
    public class Logger
    {
        private Logger()
        {
        }

        public void Write(string mesaj)
        {
            if (_instance != null)
                Console.WriteLine("Logged");
        }

        private static Logger _instance;

        public static Logger Instance
        {
            get
            {
                //double check
                if (_instance == null)
                {
                    lock (new object())
                    {
                        if (_instance == null)
                        {
                            _instance = new Logger();
                        }
                    }
                }
                return _instance;
            }
        }
    }
}

Resources:
Sefer Algan OOP training.
C-Sharp Agile Principles Patterns and_Practices book.
Gang of four book.
Oreilly Head First Object Oriented Analysis and Design book.

http://www.oodesign.com

Rastgele Yazılar

Singleton Implementation ile Benzer Yazılar:

4 December 2011 Saat : 9:16

Singleton Implementation Yazısı için Yorum Yapabilirsiniz

 Son Yazılar FriendFeed
reklam
seo kitabı
reklam
reklam

Translate

EnglishFrenchGermanItalianPortugueseRussianSpanishTurkish