zoukankan      html  css  js  c++  java
  • 【设计模式】 单例模式

    【设计模式】 单例模式 (类只允许实例化一次)

    一. 代码实现

      1. 私有构造函数 + 私有静态变量 + 公开静态函数

        a. 代码简洁,但使用静态变量和静态函数会一直占用内存,不过已现在的硬件配置,无所谓了

        b. 代码

      

            private SingletonClass() { }
            private static SingletonClass Instance = new SingletonClass();
            public static SingletonClass GetInstance()
            {
                return Instance;
            }

      2. 双判断 + 单锁  

            private static SingletonClass _instance;
            private static readonly object LockObj = new object();
            public static SingletonClass GetInstance()
            {
                if (_instance == null)
                {
                    lock (LockObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new SingletonClass();
                        }
                    }
                }
                return _instance;
            }

      3.  泛型单例

      

        public class Singleton<T> where T : new()
        {
            private static T _instance = new T();
            private static readonly object _lockObj = new object();
            private Singleton(){}
            public static T GetInstance()
            {
                if (_instance == null)
                {
                    lock (_lockObj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

      二. 使用场景

      1. 顾名思义,一个类只允许拥有一个实例

     

  • 相关阅读:
    [leetcode]Valid Number
    [leetcode]Edit Distance
    [leetcode]Decode Ways
    [leetcode]Maximum Depth of Binary Tree
    [topcoder]BadNeighbors
    [topcoder]ZigZag
    [leetcode]Subsets II
    [leetcode]Merge Sorted Array
    [leetcode]Binary Tree Maximum Path Sum
    hdu 2964 Prime Bases(简单数学题)
  • 原文地址:https://www.cnblogs.com/fzz2727551894/p/4118495.html
Copyright © 2011-2022 走看看