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

        }

  • 相关阅读:
    2020软件工程最后一次作业
    常用的10种算法

    赫夫曼编码
    哈希表(散列)
    查找算法
    排序算法
    递归

    软件工程最后一次作业
  • 原文地址:https://www.cnblogs.com/hometown/p/3204225.html
Copyright © 2011-2022 走看看