书名:设计模式之禅 作者:秦小波 出版社:机械工业出版社

    确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例

2 UML类图

06002001单例模式C#实现版本

 

图1-1 单例模式类图

代码

    Singleton.cs类

  

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

namespace china.sichuan.deyang.Singleton
{
    /// <summary>
    /// 推荐的单例模式实现类
    /// </summary>
    public class Singleton
    {
        private static Singleton singleton = new Singleton();

        /// <summary>
        /// 构造函数,限制产生多个对象
        /// </summary>
        private Singleton()
        {
            //// 这句是提示信息
            Console.WriteLine("调用Singleton的构造函数");
        }

        /// <summary>
        /// 通过该方法获得实例对象
        /// </summary>
        /// <returns></returns>
        public static Singleton GetInstance()
        {
            return singleton;
        }
    }
}
View Code

相关文章:

  • 2021-07-07
  • 2022-12-23
  • 2022-12-23
  • 2021-09-26
  • 2021-11-15
  • 2021-05-20
  • 2022-01-20
猜你喜欢
  • 2022-12-23
  • 2022-02-25
  • 2021-09-28
  • 2021-05-18
  • 2021-07-17
相关资源
相似解决方案