单例模式:确保一个类只有一个实例,并提供一个全局访问点
单例有两种方法:1延迟加载,2非延迟加载
package com.em.singleton;
/**
* Created by Administrator on 2017/12/23.
*/
public class Singleton {
/*
* 必须是私有构造方法
* */
private Singleton(){}
/**
*
* 非延迟加载
* **/
private static Singleton singleton1 = new Singleton();
public static Singleton getInstance1(){
return singleton1;
}
/**
* 延迟加载
*
* **/
private static volatile Singleton singleton; //volatile 多线程情况下保证内存可见性
public static Singleton getInstance(){
if(singleton ==null){
synchronized (Singleton.class){ //双重加锁,防止多线程同时访问
if(singleton==null){
singleton = new Singleton();
return singleton;
}
}
}
return singleton;
}
}