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
  • 相关阅读:
    概率论
    计算机网络基础
    数据库 数据库管理系统 数据库系统
    第二次冲刺总结
    Beta版总结会议
    Beta阶段项目总结
    beta版本“足够好”/测试矩阵
    zencart批量更新后台邮箱地址sql
    php首页定向到内页代码
    用.htaccess 禁止IP访问
  • 原文地址:https://www.cnblogs.com/insus/p/8023121.html
Copyright © 2011-2022 走看看