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

    单体应用下的单例模式

    /**
     * 单机版本下的单例模式
     * @author Administrator
     *
     */
    public class SingletonDemo {
        
        private static SingletonDemo instance = null;
        
        private SingletonDemo(){
            System.out.println("我是构造函数-----");
        }
        
        private static SingletonDemo getInstance() {
            if (instance == null) {
                System.out.println("我是构造方法");
                instance = new SingletonDemo();
            } 
            return instance;
        }
        
        public static void main(String[] args) {
            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance());
        }
    
    }

    多线程下的单例模式

    /**
     * 多线程下的单例模式
     * @author Administrator
     *
     */
    public class SingletonDemo2 {
    
        private static volatile SingletonDemo2 instance = null;
        
        private SingletonDemo2(){
            System.err.println("创建单例模式");
        }
        
        //DCL (double check lock  双端检锁机制)
        public static SingletonDemo2 getInstance(){
            if (instance == null) {
                synchronized (SingletonDemo2.class) {
                    if (instance == null) {
                        instance = new SingletonDemo2();
                        
                    }
                }
            }
            return instance;
            
        }
        
        public static void main(String[] args) {
            for (int i = 0; i < 100000; i++) {
                
                System.err.println(SingletonDemo2.getInstance() == SingletonDemo2.getInstance());
            }
        }
    }
  • 相关阅读:
    WPF ViewModel 调用任意前台控件的方法
    xxxx
    modelsim一些error(warning)的原因
    [verilog] inout端口处理
    [c语言]指针数组和数组指针
    电机控制术语
    MAC和PHY关系
    IAR map文件说明
    [corterm3]汇编语法
    TI 2802x系列中断系统及应用
  • 原文地址:https://www.cnblogs.com/keiyoumi520/p/13408143.html
Copyright © 2011-2022 走看看