设计模式-单例模式

时间:2021-07-31
本文章向大家介绍设计模式-单例模式,主要包括设计模式-单例模式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
单例模式是什么?
保证一个类仅有一个实例,并提供一个访问它的全局访问点,当某些类创建对象内存开销消耗大时可以考虑使用该模式
应用场景:
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 }
饿汉和懒汉的区别:
饿汉式是类一加载就实例化的对象,要提前占用资源,懒汉会有多线程访问的问题。通常情况下,饿汉式已满足需求。
以上,仅用于学习和总结!

原文地址:https://www.cnblogs.com/ywkcode/p/15085223.html