单例模式

单体应用下的单例模式

/**
 * 单机版本下的单例模式
 * @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());
        }
    }
}

 

posted @ 2020-07-31 10:12  清风商  阅读(136)  评论(0编辑  收藏  举报