singleton,design pattern

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)
        {
           
           
        }
    }
}

你可能感兴趣的:(design pattern)