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 }
     
    饿汉和懒汉的区别:
    饿汉式是类一加载就实例化的对象,要提前占用资源,懒汉会有多线程访问的问题。通常情况下,饿汉式已满足需求。
     
    以上,仅用于学习和总结!

  • 相关阅读:
    C#学生管理系统/学习
    ESC socket通信不通问题
    JavaWeb/ No 'Access-Control-Allow-Origin' header is present on the requested resource
    JavaWeb/ forward跳转到jsp页面后出现中文乱码问题
    JavaWeb/ MVC模式的初次实践
    docker搭建常用应用以及遇到的坑
    突验 8 进程通信
    实验七 信号
    实验6进程基础
    实验5 shell脚本编程
  • 原文地址:https://www.cnblogs.com/ywkcode/p/15085223.html
Copyright © 2011-2022 走看看