zoukankan      html  css  js  c++  java
  • 单例模式之懒饿汉模式简介

     

     单例模式的概念:

    单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。

    关键点:

    1)一个类只有一个实例,这是最基本的

    2)它必须自行创建这个实例
    3)它必须自行向整个系统提供这个实例

    两种实现方式:懒汉式和饿汉式单例模式

    双重检查锁(DCL)实现单例模式,虽然解决了线程不安全的问题,以及保证了资源的懒加载,在需要的时候,才会进行实例化的操作。
    但是在某些情况下(比如JDK低于1.5)会出现DCL失效,所以有一种很简洁且依旧是懒加载的方法实现单例模式。写法如下所示:
     1  1 public class Singleton {//懒汉式单例模式
     2  2     private static Singleton singleton = null;
     3  3 
     4  4     public Singleton() {
     5  5     }
     6  6 
     7  7     public static synchronized Singleton getSingleton() {
     8  8         if (singleton == null) {
     9  9             singleton = new Singleton();
    10 10         }
    11 11         return singleton;
    12 12     }
    13 13     public static class EhSingleton{//饿汉式单例模式
    14 14         private static EhSingleton eh = new EhSingleton();
    15 15         public EhSingleton(){}
    16 16         public static EhSingleton getEhSingleton(){
    17 17             return eh;
    18 18         }
    19 19     }
    20 20     public static class Doubleli {//懒汉式实现单例模式使用双重加锁机制
    21 21         private static volatile Doubleli dl = null;
    22 22         public Doubleli(){}
    23 23         public static Doubleli getInstance(){
    24 24             if(dl == null){
    25 25                 synchronized (Doubleli.class) {
    26 26                     if(dl == null){
    27 27                         dl = new Doubleli();
    28 28                     }
    29 29                 }
    30 30             }
    31 31             return dl;
    32 32         }
    33 33     }
    34 34 }
    View Code
  • 相关阅读:
    mysql 函数 存储过程 事件(event) job 模板
    protobuf 无proto 解码 decode 语言 java python
    mitmproxy fiddler 抓包 填坑
    android adb 常用命令
    android机器人 模拟 踩坑过程
    RabbitMQ添加新用户并支持远程访问
    Windows下RabbitMQ安装及配置
    Java mybatis mysql 常用数据类型对应关系
    easyExcel 踩坑
    linux防火墙查看状态firewall、iptable
  • 原文地址:https://www.cnblogs.com/yshang/p/9414429.html
Copyright © 2011-2022 走看看