zoukankan      html  css  js  c++  java
  • 单例模式

    创建型模式:主要聚焦于对象是如何创建的。

    单例模式,在任何情况下,只允许有一个对象的实例。

    1.       单线程下的单例模式:

    public class SingletonTest

        {

            private static SingletonTest instance;

            private SingletonTest() { }

            public static SingletonTest Instance

            {

                get

                {

                    if (instance == null)

                    {

                        instance = new SingletonTest();

                    }

                    return instance;

                }

            }

    }

    2.       多线程情况下的单例模式:

    public class SingleTestThread

        {

            private static volatile SingleTestThread instance;

            private static object lockHelper = new object();

            private SingleTestThread() { }

            public static SingleTestThread Instance

            {

                get

                {

                    if (instance == null)

                    {

                        lock (lockHelper)

                        {

                            if (instance == null)

                            {

                                instance = new SingleTestThread();

                            }

                        }

                    }

                    return instance;

                }

            }

        }

    3.任何情况下都可以用,但是没办法传参:

    public class SingleSimple

        {

            private SingleSimple() { }

            public static readonly SingleSimple Instance = new SingleSimple();

        }

  • 相关阅读:
    thinkphp 防止sql注入
    Thinkphp模板怎么使用自定义函数
    Jquery 获取文件内容
    php,Allowed memory size of 8388608 bytes exhausted (tried to allocate 1298358 bytes)
    thinkphp 定位查询 Model:last您所请求的方法不存在!
    if condition volist
    thinkPHP 无法create,无法插入数据,提示非法数据对象
    eclipse 最有用的10个快捷键
    button 禁止
    thinkphp显示重复两次
  • 原文地址:https://www.cnblogs.com/hometown/p/3204225.html
Copyright © 2011-2022 走看看