• 用C#改写Head First Design PatternsSingleTon(原创)


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace SingleTon
    {
        public sealed class SingleObject
        {
            //公有字段
            public string name;


            //类似java的实现
            private static object syncRoot = new Object();
           
            //私有字段
            private volatile static SingleObject uniqueObj;

            private SingleObject(string name)
            {
                this.name = name;
            }

            public static SingleObject getInstance(string n)
            {
                if (uniqueObj == null)
                {
                    //lock (typeof(SingleObject))
                    lock (syncRoot)
                    {
                        uniqueObj = new SingleObject(n);
                    }
                }

                return uniqueObj;
            }

           
            //private static readonly SingleObject instance = new SingleObject();
            //private SingleObject() { }
            //public static SingleObject Instance
            //   {
            //      get 
            //      {
            //         return instance; 
            //      }
            //   }

        }
    }

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace SingleTon
    {
        class Program
        {
            static void Main(string[] args)
            {
                SingleObject s = SingleObject.getInstance("a");
                SingleObject s1 = SingleObject.getInstance("b");

                System.Console.WriteLine(s.name);
                System.Console.WriteLine(s1.name);

                System.Console.ReadLine();

            }
        }
    }

    关于作者: 王昕(QQ:475660) 在广州工作生活30余年。十多年开发经验,在Java、即时通讯、NoSQL、BPM、大数据等领域较有经验。
    目前维护的开源产品:https://gitee.com/475660
  • 相关阅读:
    [java]struts2入门
    [c#基础]ICloneable接口
    idea jsp html 空白页的问题
    在Intellij Idea中使用jstl标签库
    org.apache.catalina.LifecycleException: Failed to start component
    tomcat点击startup.bat一闪而退的方法
    [转]小心C# 5.0 中的await and async模式造成的死锁
    体验h5离线缓存
    [Asp.net core]使用Polly网络请求异常重试
    asp.net core读取appsettings.json,如何读取多环境开发配置
  • 原文地址:https://www.cnblogs.com/starcrm/p/1519229.html
Copyright © 2020-2023  润新知