单例的种种情况

本文详细介绍了单例模式的概念及其在不同场景下的实现方法,包括如何通过构造函数限制外部实例化、使用方法或属性获取唯一实例,以及在多线程环境中确保实例的安全创建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

单例模式(单件模式)


    使用方法返回唯一的实例


    public class SingLeton
    {
        //创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
        private SingLeton()
        {
 
        }

        private static SingLeton instance;

        public static SingLeton GetInstance()
        {
            if (instance ==null )
            {
                instance = new SingLeton();
            }

            return instance;
        }

    }


    使用属性返回唯一的实例


    public class SingLeton
    {
        //创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
        private SingLeton()
        {
 
        }

        private static SingLeton instance;

        public static SingLeton Instance
        {
            get
            {
                if (instance==null )
                {
                    instance = new SingLeton();
                }
                return instance;
            }
        }

    }


    多线程访问时需要对实例进行加锁

    public class SingLeton
    {
        //创建一个私有的构造函数(必须),堵住外界使用new创建此实例的可能
        private SingLeton()
        {
 
        }

        private static SingLeton instance;

        //定义一个辐助对象
        private static object obj = new object();

        //多线程使用单例模式(double check 双重检查)
        public static SingLeton GetInstances()
        {
            if (instance ==null )
            {
                lock (obj)  //为实例加锁
                {
                    if (instance ==null)
                    {
                        instance = new SingLeton();
                    }
                }
            }
            return instance;
        }

    }


    在C#与公共语言运行库也提供了一种“静态初始化”方法,这种方法不需要开发人员显式地编写线程安全代码,即可解决多线程环境下它是不安全的问题

     public sealed class Singleton
    {
        //1.使用readonly的方式
        private static readonly Singleton instance = new Singleton();

        private Singleton()
        {
 
        }

        public static Singleton GetInstance()
        {
            return instance;
        }
    }

    由于这种静态初始化方式是自己被加载时就将自己实例化,所以被形象地称之为饿汉式单例类,上面两种处理方式是要在第一次被引用时,才会将自己实例化,所以就被称为懒汉式单例类。

    由于饿汉式,即静态初始化方式,是类一加载就实例化,所以要提前占用系统资源,然而懒汉式,又会面临多线程访问安全性的问题,需要双重锁定的处理才可以保证安全。所在到底使用哪一种方式,取决于实际的需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值