zoukankan      html  css  js  c++  java
  • 设计模式学习总结(四)单例模式

       单例模式即一个类只能有一个实例,并且需该类自动提供该实例。

      一、示例展示:

      通过学习及总结,以下是我做的两个单例模式的示例:

      懒汉式的单例模式:

    using System;
    
    namespace DesignModel
    {
        class Program
        {
            static void Main(string[] args)
            {
                Singleton sl1 = Singleton.GetInstance();
                Singleton sl2 = Singleton.GetInstance();
                if (sl1 == sl2)
                {
                    Console.WriteLine("The two instance is identical!");
                }
                Console.ReadLine();
            }
        }
    
        class Singleton
        {
            private static Singleton Instance;
            private Singleton()
            {
    
            }
    
            public static Singleton GetInstance()
            {
                if (Instance == null)
                {
                    Instance= new Singleton();
                }
                return Instance;
            }
        }
    }
    View Code

          饿汉式的单例模式:

    using System;
    
    namespace DesignModel
    {
        class Program
        {
            static void Main(string[] args)
            {
                Singleton sl1 = Singleton.GetInstance();
                Singleton sl2 = Singleton.GetInstance();
                if (sl1 == sl2)
                {
                    Console.WriteLine("The two instance is identical!");
                }
                Console.ReadLine();
            }
        }
    
        class Singleton
        {
            private static Singleton Instance = new Singleton();
            private Singleton()
            {
    
            }
    
            public static Singleton GetInstance()
            {
                return Instance;
            }
        }
    }
    View Code

      懒汉式的单例模式与饿汉式的单例模式的主要区别:懒汉式的单例模式在每次加载自己时就会进行实例化,而汉式的单例模式则会去进行判断,如果当前实例为空,则才会进行实例化;

      二、单例模式设计理念:

      私有的构造函数,以及可供外部访问的静态方法。

      三、角色及关系:

      

  • 相关阅读:
    [USACO][最短路]Cow Tours
    [USACO][枚举]Preface Numbering
    [USACO][枚举]Hamming Code
    [USACO][枚举]Healthy Holsteins
    [USACO][DAG上的动态规划]Sorting A Three-Valued Sequence
    [USACO][暴力]The Castle
    [USACO][枚举]Ski Course Design
    运算符重载must take either zero or one argument错误
    关于js鼠标事件综合各大浏览器能获取到坐标的属性总共以下五种
    鼠标滚轮事件封装
  • 原文地址:https://www.cnblogs.com/sccd/p/6577043.html
Copyright © 2011-2022 走看看