• 设计模式之—单例模式<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

    测试结果

    要么忍,要么狠,要么滚!
  • 相关阅读:
    C++ Boost 函数与回调应用
    C++ Boost库 操作字符串与正则
    C++ Boost库 实现命令行解析
    PHP 开发与代码审计(总结)
    c strncpy函数代码实现
    c strcat函数代码实现
    c strcpy函数代码实现
    c strlen函数代码实现
    Java-IO流-打印流
    Java-IO流-文件复制2
  • 原文地址:https://www.cnblogs.com/zxd543/p/3260767.html
Copyright © 2020-2023  润新知