设计模式系列一:单例模式

单例模式
主要用于保证一个类只有一个实例,对外提供一个全局的访问点来获取该实例。是所有设计模式中最简单的模式。
设计模式系列一:单例模式_第1张图片
实现代码(c#)

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

namespace Singleton
{
    /// 
    /// 功能描述:单例模式示例
    /// 优点:对外保证提供唯一实例
    /// 缺点:获取实例时需要花销时间,采用加锁技术,在多线程访问时花费的时间较多
    /// 
    class Singleton
    {
        //存放本类私有对象
        private static Singleton m_SingletonInstance;
        //线程锁
        private static readonly object m_myLock=new object();

        /// 
        /// 私有构造函数
        /// 阻止类的外部创建本类实例
        /// 
        private Singleton()
        {

        }

        /// 
        /// 返回本类唯一实例
        /// 添加多线程防护
        /// 
        /// 本类实例
        public static Singleton GetInstance()
        {
            if(m_SingletonInstance==null)//先判断实例是否存在
            {
                lock (m_myLock)//加锁,防护多线程访问
                {
                    if (m_SingletonInstance == null)//防止创建多个实例
                    {
                        m_SingletonInstance = new Singleton();//创建实例
                    }
                }
            }
            return m_SingletonInstance;
        }
    }
}

你可能感兴趣的:(设计模式学习系列)