zoukankan      html  css  js  c++  java
  • 单例

    单例

    public class Singleton {
    
       
        public static int STATUS = 1;
        private Singleton() {
        System.out.println("Singleton is created");
        }
        private static Singleton instance = new Singleton();
        public static Singleton getInstance() {
        return instance;
        }
        public static void main(String[] args) {
        //任何对Singleton方法或字段的应用,都会导致类初始化,并创建instance实例
        System.out.println(Singleton.STATUS);
        //但是类初始化只有一次,因此instance试了永远只会被创建一次,所以调用Singleton.getInstance()
        //不会输出 Singleton is created
        Singleton.getInstance();
        }
    
    }

    延迟加载

    public class LazySingleton {
    
        public static int STATUS = 1;
        private LazySingleton() {
        System.out.println("LazySingleton is create");
        }
        private static LazySingleton instance = null;
        public static synchronized LazySingleton getInstance() {
        if(instance == null) {
            instance = new LazySingleton();
        }
        
        return instance;
        }
        public static void main(String[] args) {
    
        System.out.println(LazySingleton.STATUS);
        //延迟加载,只会在instance被第一次使用时,创建对象
        //因此,只有调用getInstance()方法时才会创建对象
        LazySingleton.getInstance();
        }
    
    }

    加强版单例

    综合上述 Singleton 和 LazySingleton 优点的单例

    /**
     * 拥有Singleton 和 LazySingleton 的优点
     * Singleton 优点: getInstance() 没有使用Synchronized 加锁
     * LazySingleton 优点:直到instance 实例被使用时,才创建instance 对象
     *
     */
    public class StaticSingleton {
    
        public static int STATUS = 1;
        private StaticSingleton() {
        System.out.println("StaticSingleton is create");
        }
        
        private static class SingletonHolder {
        private static StaticSingleton instance = new StaticSingleton();
        }
        
        public static StaticSingleton getInstance() {
        return SingletonHolder.instance;
        }
        public static void main(String[] args) {
        System.out.println(StaticSingleton.STATUS);
        StaticSingleton.getInstance();
        }
    
    }
  • 相关阅读:
    Oracle EBS Form调用JavaBean前期配置
    Oracle EBS Form Builder使用Java beans创建窗体
    将 Oracle Forms 集成到 Oracle ADF Faces 中
    Oracle EBS开发习惯
    支持MOAC功能的Form开发步骤
    Form的Trigger的优先级
    所有标准API
    EBS中Java并发程序笔记(1)
    ORACLE FORM中,如何使用警告?
    .Net Core3.0 WebApi 六: Sqlsugar+异步泛型仓储
  • 原文地址:https://www.cnblogs.com/luffystory/p/11944192.html
Copyright © 2011-2022 走看看