• 设计模式:单例


    单例模式  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;
                        }
                    }
                }
            }
        }

    使用场合:

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

  • 相关阅读:
    Python异步任务模块之-celery
    Atom 编辑器侧边栏忽略隐藏文件
    判断字符串是否为回文 python
    python 命令行工具 fire
    Appium自动化测试-iOS
    视频转换工具ffmpeg
    nodejs顺序执行shell
    Jenkins 邮箱配置及问题解决
    mac配置php
    appium镜像设置
  • 原文地址:https://www.cnblogs.com/Francis-YZR/p/4770972.html
Copyright © 2020-2023  润新知