创建型设计模式之单例设计模式

概念解释:确保一个类只有一个实例,并提供一个全局访问点。

应用场景
1.多线程的线程池,方便控制及节约资源。
2.windows电脑的任务管理器就是,不信你试试。
3.windows电脑的回收站也是。
4.数据库的连接池设计,一般也采用单例设计模式,数据库连接是一种数据库资源。在数据库软件系统中
使用数据库连接池,可以节省打开或关闭数据库连接引起的效率损耗,用单例模式维护,就可以大大降低这种损耗。
5.应用程序的日志应用,由于共享的日志文件一直处于打开状态,只能有一个实例去操作,否则内容不好追加。

为了便于理解代码示例如下:

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

namespace SingleTon
{
   public sealed class Singleton
    {
        static Singleton instance = null;
        private static readonly object padlock = new object();
        private Singleton()
        {
        }
        public static Singleton Instance
        {
            get {
                if (instance == null)
                {
                    lock(padlock)//如果考虑多线程,加锁是很好的解决方案
                    {
                        if(instance == null)
                        { 
                        instance = new Singleton();
                        }
                    }
                }
                return instance;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/zylstu/p/10013247.html