1.静态:

C#-使用单例模式_业务需求

引自: 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()
        {

        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

作者:꧁执笔小白꧂