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

    单例模式的多种实现方式

      1.饿汉模式 

    public class Singleton {
    
        private static Singleton singleton = new Singleton();
    
        private Singleton(){}
    
        public static Singleton getInstance(){
            return singleton;
        }
    
    }
    

      

      2.懒汉模式

    public class Singleton {
    
        private static Singleton singleton;
    
        private Singleton() {}
    
        synchronized public static Singleton getInstance(){
            if(singleton!=null){
            }else{
                singleton =  new Singleton();
            }
            return singleton;
        }
    
    }
    

      

      3. 双重校验锁

    public class Singleton {
    
        private static Singleton singleton;
    
        private Singleton() {}
    
         public static Singleton getInstance(){
            if(singleton!=null){
            }else{
                synchronized (Singleton.class){
                    if(singleton==null){
                        Singleton =  new Singleton();
                    }
                }
    
            }
            return Singleton;
        }
    }
    

      

      4.静态内部类

    public class Singleton {
    
        private static class SingletonHandle{
            private static Singleton singleton = new Singleton();
        }
    
        private Singleton(){}
    
        public static Singleton(){
            return SingletonHandle.singleton;
        }
    
    }
    

      

  • 相关阅读:
    序列终结者
    CF696C PLEASE
    [清华集训]Rmq Problem / mex
    CF786B Legacy
    链表结构详解
    synchronized同步方法和同步代码块的区别
    关于守护线程定义
    线程的优先级
    mysql查询当天的数据
    java以正确的方式停止线程
  • 原文地址:https://www.cnblogs.com/ppli/p/5287294.html
Copyright © 2011-2022 走看看