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
  • 相关阅读:
    计算机视觉(四)
    计算机视觉(三)
    计算机视觉(二)
    计算机视觉(一)
    基于opencv3实现运动物体识别
    tensorRT程序设计框架_4
    Cuda程序的设计-2
    神经网络的快速体验
    STL简介_18
    函数模板-17
  • 原文地址:https://www.cnblogs.com/insus/p/8023121.html
Copyright © 2011-2022 走看看