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

    // 饿汉模式
    public class Singleton{
      // 私有化默认构造函数,防止独自创建对象
      private Singleton(){
        
      }
      // 饿汉饿极了,上来直接就开'吃'了,虚拟机启动就创建实例对象
      private static Singleton instance = new Singleton();
      // 返回实例
      public static Singleton getInstance(){
        return instance;
      }
    }
    // 懒汉模式(多线程会出问题)
    public class Singleton{
      // 私有化默认构造函数,防止独自创建对象
      private Singleton(){
        
      }
      // 懒汉比较懒,不创建实例对象,用的时候再创建
      private static Singleton instance;
      
      public static Singleton getInstance(){
        if(instance == null){
           instance = new Singleton();
        }
        return instance;
    }
    // 懒汉双检锁,避免多线程导致并发问题
    pulblic class Singleton{
        private Singleton(){};
    
        private volatile static Singleton instance;
    
        public static Singleton getInstance(){
            if(instance == null){
                Synchronized(Singleton.class){
                      if(instance == null){
                          instance = new Singleton();   
                      }  
                }
            }
            return instance;  
        }          
    }
  • 相关阅读:
    清除陷入CLOSE_WAIT的进程
    Eclipse
    远程连接elasticsearch遇到的问题
    Linux环境Nginx安装
    CentOS安装mysql
    py2exe使用方法
    Python3.4如何读写Excel
    getPhysicalNumberOfCells 与 getLastCellNum的区别
    浅析MySQL中exists与in的使用
    【MongoDB for Java】Java操作MongoDB
  • 原文地址:https://www.cnblogs.com/wsZzz1997/p/14581683.html
Copyright © 2011-2022 走看看