zoukankan      html  css  js  c++  java
  • 单例模式(C#)

    学习设计模式,一直没有机会写一个单例模式。

    今天在控制台应用程序,写个简单的例子,Hi与Hello。

     public sealed class At
        {
            private static At instance = null;
            public static At Instance
            {
                get
                {
                    if (instance == null)
                    {
                        instance = new At();
                    }
                    return instance;
                }
            }
    
            public void Hello()
            {
                Console.WriteLine("Hello");
            }
    
            public void Hi()
            {
                Console.WriteLine("Hi");
            }
        }
    Source Code

    测试:

    单例类,宣告为sealed,也就是说阻止其他类从该类继承。对象只是本身。

    考虑到线程安全,可以有代码中,添加几行代码:

    public sealed class At
        {
            private static At instance = null;
            private static readonly object threadSafeLock = new object();
            public static At Instance
            {
                get
                {
                    lock (threadSafeLock)
                    {
                        if (instance == null)
                        {
                            instance = new At();
                        }
                        return instance;
                    }
                }
            }
    
            public void Hello()
            {
                Console.WriteLine("Hello");
            }
    
            public void Hi()
            {
                Console.WriteLine("Hi");
            }
        }
    Source Code

    下面内容于2017-12-12 08:10分添加:
    补充,上面的写法是每次加锁,性能多少有些损失。 解决此问题可以加个判断对象没有实例化时加锁。

    public static At Instance
            {
                get
                {
                    if (instance == null)
                    {
                        lock (threadSafeLock)
                        {
                            if (instance == null)
                            {
                                instance = new At();
                            }
                        }
                    }
                    return instance;
                }
            }
    Source Code
  • 相关阅读:
    深拷贝浅拷贝的探索以及实现
    Vue之动态class写法总结
    hh
    90%的新媒体人都在用的标题套路!
    研究999篇100W+爆款文,标题之总结
    想突破10w+?先过了这一关……
    易撰数据分析,做精准爆文分析!
    清除.bat
    截图.bat
    Git 学习笔记(二)分支管理
  • 原文地址:https://www.cnblogs.com/insus/p/8023121.html
Copyright © 2011-2022 走看看