一、.Net基础【1.9】单例模式

1.为什么要使用单例模式?

有的类在系统中只能有一个对象(*,资源管理器、缓存管理器等),这时就要使用“单例模式”(singleton)。

2.实现单例模式

实现单例模式有很多方法,先介绍最简单、最实用的“饿汉式”。

构造函数声明为private,这样避免外界访问,定义一个private readonly static的对象实例,static成员的初始化只在类第一次使用的时候执行一次。readonly修饰变量只能在构造函数或者初始化的时候赋值。定义一个public static的getInstance方法,返回唯一实例

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

namespace console2
{
    class SingleInstance
    {
        private static readonly SingleInstance singleInstance = new SingleInstance();
        private SingleInstance()
        {
        }
        public static SingleInstance GetInstance()
        {
            return singleInstance;
        }
    }
}
原文地址:https://www.cnblogs.com/lolitagis02/p/8094890.html