• 设计模式:单例


    单例模式  Singleton Pattern

     

    确保某一个类只有一个实例, 且自行实例化并向整个系统提供这个实例.

    相信这个很多人都会,直接代码:

    class Program
        {
            static void Main(string[] args)
            {
                Test t = Test.getInstance();
                Test t1 = Test.getInstance();
                if (t == t1)
                {
                    Console.Write("一样的 ");
                }
                Console.ReadKey();
            }
            public class Test
            {
                public static Test t = null;
                //锁对象
                public readonly static object l = new Object();
                private Test()
                {
                    //单例,执行一次构造函数
                    Console.Write("------singleton---- ");
                }
                public static Test getInstance()
                {
                    //加锁处理多并发问题
                    lock (l)
                    {
                        if (t == null)
                        {
                            t = new Test();
                            return t;
                        }
                        else
                        {
                            return t;
                        }
                    }
                }
            }
        }

    使用场合:

    当在系统中某个特定的类对象实例只需要有一个的时候,可以使用单例设计模式,只有真正需要”单一实例”的时候才使用.

  • 相关阅读:
    nginx负载均衡
    saltstack高效运维
    nginx入门与实战
    web service基础知识
    centos tomcat解压版安装
    centos yum 安装jdk1.7
    centos7安装opencv3.4.1(同样适用于最新版本4.2.0)
    正向代理与反向代理,正向代理与反向代理的应用
    MySQL日期 字符串 时间戳互转
    idea svn提交时,performing vcs refresh时间很长的解决办法
  • 原文地址:https://www.cnblogs.com/Francis-YZR/p/4770972.html
Copyright © 2020-2023  润新知