zoukankan      html  css  js  c++  java
  • 创建型设计模式之单例设计模式

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

    应用场景
    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;
                }
            }
        }
    }
  • 相关阅读:
    11 数值的整数次方
    10 二进制中1的个数
    6 重建二叉树
    5 从尾到头打印链表
    计算机网络面试题
    Http和Https的区别
    UVALive 7749 Convex Contour (计算几何)
    Gym 101190H Hard Refactoring (模拟坑题)
    UVa 11324 The Largest Clique (强连通分量+DP)
    HDU 6006 Engineer Assignment (状压DP)
  • 原文地址:https://www.cnblogs.com/zylstu/p/10013247.html
Copyright © 2011-2022 走看看