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

    单例模式是什么?
    保证一个类仅有一个实例,并提供一个访问它的全局访问点,当某些类创建对象内存开销消耗大时可以考虑使用该模式
     
    应用场景:
    1)资源的共享
    2)数据库连接池的设计
     
    单例模式分为饿汉式懒汉式
     
    1.饿汉式单例类 -自己被加载时就将自己实例化
     1 /// <summary>
     2 /// 饿汉模式
     3 /// </summary>
     4 public class SingletonTest
     5 {
     6     private static SingletonTest instance=new SingletonTest();
     7 
     8     private SingletonTest() { }
     9 
    10     public static SingletonTest GetInstance()
    11     {
    12         return instance;
    13     }
    14 }
    C# 静态初始化
     1 public sealed class SingletonTest
     2 {
     3     private static readonly SingletonTest instance = new SingletonTest();
     4 
     5     private SingletonTest() { }
     6 
     7     public static SingletonTest GetInstance()
     8     {
     9         return instance;
    10     }
    11 }
    其中关键词sealed,阻止发生派生
     
    2.懒汉式单例类-第一次引用时,才会将自己实例化
     1 //懒汉模式
     2 public class SingletonTest
     3 {
     4     private static SingletonTest instance;
     5 
     6     private SingletonTest() { }
     7 
     8     public static SingletonTest GetInstance()
     9     {
    10         if (instance == null)
    11         {
    12             instance = new SingletonTest();
    13         }
    14         return instance;    
    15     }
    16 }
    产生问题:多线程下不安全,解决方式:双重锁定
     1 public class SingletonTest
     2 {
     3     private static SingletonTest instance;
     4     private static readonly object syncRoot = new object();
     5     private SingletonTest() { }
     6 
     7     public static SingletonTest GetInstance()
     8     {
     9 
    10         if (instance == null)
    11         {
    12             lock (syncRoot)
    13             {
    14                 if (instance == null)
    15                 {
    16                     instance = new SingletonTest();
    17                 }
    18             } 
    19         }
    20         return instance;    
    21     }
    22 }
     
    饿汉和懒汉的区别:
    饿汉式是类一加载就实例化的对象,要提前占用资源,懒汉会有多线程访问的问题。通常情况下,饿汉式已满足需求。
     
    以上,仅用于学习和总结!

  • 相关阅读:
    Selenium等待:sleep、隐式、显式和Fluent
    开源礼节
    IntelliJ中基于文本的HTTP客户端
    Selenium4 IDE特性:弹性测试、循环和逻辑判断
    CF 1400G.Mercenaries 题解【SOSDP 组合数学】
    Educational Codeforces Round 33
    Educational Codeforces Round 32
    Educational Codeforces Round 31
    Educational Codeforces Round 30
    Educational Codeforces Round 29
  • 原文地址:https://www.cnblogs.com/ywkcode/p/15085223.html
Copyright © 2011-2022 走看看