zoukankan      html  css  js  c++  java
  • 单例模式的多种实现方式

    //需要时加锁,双重校验
    class CustomSingleton{
    
       private static CustomSingleton customSingleton = null;
    
       private CustomSingleton(){};
    
       public static CustomSingleton getCustomSingleton(){
          if(customSingleton==null){
             synchronized (CustomSingleton.class) {
                if(customSingleton==null) {
                   customSingleton = new CustomSingleton();
                }
             }
          }
          return customSingleton;
       }
    }
    
    /*
    //需要时加锁,有并发问题
    class CustomSingleton{
    
       private static CustomSingleton customSingleton = null;
    
       private CustomSingleton(){};
    
       public static CustomSingleton getCustomSingleton(){
          if(customSingleton==null){
             synchronized (CustomSingleton.class) {
                customSingleton = new CustomSingleton();
             }
          }
          return customSingleton;
       }
    }*/
    
    /*
    //不加锁,有并发问题
    class CustomSingleton{
    
       private static CustomSingleton customSingleton = null;
    
       private CustomSingleton(){};
    
       public static CustomSingleton getCustomSingleton(){
          if(customSingleton==null){
             customSingleton = new CustomSingleton();
          }
          return customSingleton;
       }
    }*/
    
    /*
    //暴力同步锁
    class CustomSingleton{
    
       private static CustomSingleton customSingleton = null;
    
       private CustomSingleton(){};
    
       public static synchronized CustomSingleton getCustomSingleton(){
          if(customSingleton==null){
             customSingleton = new CustomSingleton();
          }
          return customSingleton;
       }
    }*/
    
    /*
    //线程安全  常量初始化
    class CustomSingleton{
    
       private static CustomSingleton customSingleton = new CustomSingleton();
    
       private CustomSingleton(){};
    
       public static CustomSingleton getCustomSingleton(){ return customSingleton;}
    }
    */
    
    /*
    //枚举单例
    enum CustomSingleton{
    
       SINGLETON;
    
       public void print(){
          System.out.println(123);
       }
    }*/
  • 相关阅读:
    转:python2.x 和 python3.x的区别
    迭代器
    C++学习笔记-预备知识
    phpstudy扩展mongoDB
    Linux gd库安装步骤说明
    Linux jpeglib库的安装
    github开源项目
    本地文件拖拽到虚拟机里,文件存储位置
    linux php 扩展安装
    CentOS6.10 Nginx无法解析php文件
  • 原文地址:https://www.cnblogs.com/gavinYang/p/11202246.html
Copyright © 2011-2022 走看看