代码改变世界

[原创]singleton,design pattern

2007-09-22 12:04  Virus-BeautyCode  阅读(355)  评论(0编辑  收藏  举报
thank you for your read
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    //single thread
    public class Singleton
    {
        private static Singleton instance;

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                    return new Singleton();
                return instance;
            }
        }
    }

    //multiple thread
    public class SingletonTest
    {
        private static volatile SingletonTest instance;
        private static object lockHelper = new object();

        private SingletonTest() { }

        public static SingletonTest Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (lockHelper)
                    {
                        if (instance == null)
                            return new SingletonTest();
                    }
                }
                return instance;
            }
        }
    }

    //simple singleton in vary environment
    public class SimpleSingleton
    {
        //inline instance
        public static readonly SimpleSingleton Instance = new SimpleSingleton();

        private SimpleSingleton() { }
    }

     //be equal to above
    public class singleton
    {
        public static readonly singleton instance;

        //can not have parameter, in multithread environment it can execute only once
        static singleton()
        {
            instance=new singleton();
        }

        private singleton() { }
    }

    class Program
    {
        static void Main(string[] args)
        {
           
           
        }
    }
}