【Unity】单例模式浅析

1、什么是单例模式

简单来说就是一个类只允许有一个实例对象,为达到这种目的,类的构造函数必须私有化(private),这样外界就无法实例化该类的对象。作为替代,需要在单例的类中实例化这个类的对象,外界可通过静态成员方法访问这个对象。

 

2、单例模式的常见写法

懒汉模式:只有调用GetInstance()方法才实例化对象,有点被动,所以称为懒汉模式

public class Singleton
{
     //实例化对象
    private static Singleton instance = null;           

    //私有化构造函数
    private Singleton()
    {
    }

    //外界访问单例对象的方法
    public static Singleton GetInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }
}

 

饿汉模式:在调用GetInstance()方法前就已经实例化对象,很主动,所以叫饿汉模式

public class Singleton
    {
        //事先实例化对象
        private readonly static  Singleton instance = new Singleton();

        //私有化构造函数
        private Singleton() 
        {
           
        }

        //提供静态方法使外界可以进行访问
        public static Singleton GetInstance()
        {
            return instance;
        }
    }

 

posted on 2018-10-15 16:04  real-道森  阅读(50)  评论(0)    收藏  举报