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();

        }

  • 相关阅读:
    Scala学习笔记
    flume ng 1.3 安装(转)
    学习scala trait
    scala性能测试
    scala容器使用
    hdu 4607 Park Visit
    FZU 1591 Coral的烦恼
    fzu 1675 The Seventy-seven Problem
    hdu 4602 Partition
    zoj 1842 Prime Distance
  • 原文地址:https://www.cnblogs.com/hometown/p/3204225.html
Copyright © 2011-2022 走看看