C#-使用单例模式

1.静态:

引自:https://jingyan.baidu.com/article/acf728fd0f85ddb9e510a3ee.html

2.加锁(线程安全):

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

namespace ZhibiXiaobai
{
    /// <summary>
    /// 单例模式
    /// </summary>
    internal class TestNew
    {
        /// <summary>
        /// 单例实体
        /// </summary>
        private static TestNew instance = null;

        /// <summary>
        /// 同步锁
        /// </summary>
        private static readonly object obj = new object();

        /// <summary>
        /// 单例
        /// </summary>
        internal static TestNew CreateInstance()
        {
            lock (obj)
            {
                if (instance == null)
                {
                    instance = new TestNew();
                }
                return instance;
            }
        }

        /// <summary>
        /// 实例化-写业务需求
        /// </summary>
        internal TestNew()
        {

        }
    }
}
posted @ 2021-12-20 17:48  ꧁执笔小白꧂  阅读(70)  评论(0编辑  收藏  举报