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

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

      二、单例模式设计理念:

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

      三、角色及关系:

      

  • 相关阅读:
    Python深入:编码问题总结
    Search for a Range
    Search in Rotated Sorted Array
    WebStrom 多项目展示及vuejs插件安装
    高强度减脂Tabata练习
    webStrom 美化
    myeclipse 与 webstrom 免解析node_modules 的方法
    node-webkit 入门
    vue框架搭建
    Electron_01
  • 原文地址:https://www.cnblogs.com/sccd/p/6577043.html
Copyright © 2011-2022 走看看