My tech blog and other writing

Tuesday, August 15, 2006

Nice article on the singleton pattern

http://www.yoda.arachsys.com/csharp/singleton.html

aslo check out http://www.yoda.arachsys.com/csharp/beforefieldinit.html

Here is some code you can use to test the fourth version presented... I think this implimentation is very neat and the pattern is very neat (keeps code clean). I like the way it is implimented and believe the runtime rules ensure it is thread safe but I will trust the author in this case...
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Singleton1test
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Console.WriteLine("begin " + DateTime.Now.ToString());
            Singleton s = Singleton.Instance;
            Console.WriteLine("test " + s.now);
           
            Thread.Sleep(2000);

            Singleton s2 = Singleton.Instance;
            System.Console.WriteLine("second test " + DateTime.Now.ToString());
            Console.WriteLine("test " + s2.now);

            Thread.Sleep(2000);

            Singleton s3 = Singleton.Instance;
            System.Console.WriteLine("Third test " + DateTime.Now.ToString());
            Console.WriteLine("test " + s3.now);


            while (Console.ReadLine() == "asl;difasldfljasdf" ) { }
        }
    }


    public sealed class Singleton
    {
        static readonly Singleton instance = new Singleton();

        private string somedatestring;

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Singleton()
        {
            Console.WriteLine("In static Constructor");
        }

        Singleton()
        {
            Console.WriteLine("In non-static Constructor");
            somedatestring = DateTime.Now.ToString();
        }

        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }

        public string now
        {
            get
            {
                return somedatestring;
            }
        }
    }


}

0 Comments:

Post a Comment

<< Home