zoukankan      html  css  js  c++  java
  • 设计模式之—单例模式<Singleton Pattern>

    单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    Singleton类

    提供两种单例的方式:

    namespace SingletonPattern
    {
        //懒汉式单例类
        //class Singleton
        //{
        //    private static Singleton instance;
        //    private static readonly object sysRoot = new object();
        //    private Singleton()
        //    {
        //    }
        //    public static Singleton GetInstance()
        //    {
        //        //多线程单例双重锁定 
        //        if (instance == null) //先判断实例是否存在,不存在再加锁处理
        //        {
        //            lock (sysRoot)
        //            {
        //                if (instance == null)
        //                {
        //                    instance = new Singleton();
        //                }
        //            }
        //        }
        //        return instance;
        //    }
        //}
    
        //静态初始化,饿汉式单例类
        public sealed class Singleton
        {
            private static readonly Singleton instance = new Singleton();
            private Singleton()
            { }
            public static Singleton GetInstance()
            {
                return instance;
            }
        }
    }
    View Code

    测试类:(TestMain)

    namespace SingletonPattern
    {
        class TestMain
        {
            static void Main(string[] args)
            {
                Singleton instance = Singleton.GetInstance();
                Singleton instance1 = Singleton.GetInstance();
    
                if (instance == instance1)
                {
                    Console.WriteLine("两个对象是相同的实例!");
                }
    
                Console.WriteLine();
            }
        }
    }
    View Code

    测试结果

    要么忍,要么狠,要么滚!
  • 相关阅读:
    第二阶段Sprint2
    第二阶段Sprint1
    Sprint10
    Sprint9
    Sprint8
    Sprint7
    第二阶段个人工作总结(2)
    第二阶段个人工作总结(1)
    查找三个“水王”
    构建之法阅读笔记03
  • 原文地址:https://www.cnblogs.com/zxd543/p/3260767.html
Copyright © 2011-2022 走看看