/**
* @description:单例模式:确保某一个类只有一个实例,并向全局提供一个访问实例的访问方式;
* @author: caojj
* @create: 2018-01-30 13:28
*/
//实现方式1、懒汉式,线程不安全
public class Singleton {
private static Singleton instace ;
/**
* 构造器私有,确保不会被外界实例化(反射例外)
*/
private Singleton(){}
/**
* 设置访问实例的方式
* @return
*/
public static Singleton getInstace(){
if(instace==null){
instace = new Singleton();
}
return instace;
}
}
//实现方式2、懒汉式,线程安全
public class Singleton {
//加volatile保证线程访问变量透明。防止重排序
private static volatile Singleton instace ;
/**
* 构造器私有,确保不会被外界实例化(反射例外)
*/
private Singleton(){}
/**
* 设置访问实例的方式,加锁保证线程安全
* @return
*/
public static synchronized Singleton getInstace(){
if(instace==null){
instace = new Singleton();
}
return instace;
}
}
//实现方式3、饿汉式
public class Singleton {
//基于classloader保证线程安全
private static Singleton instace = new Singleton();
/**
* 构造器私有,确保不会被外界实例化(反射例外)
*/
private Singleton(){}
/**
* 设置访问实例的方式
* @return
*/
public static Singleton getInstace(){
return instace;
}
}
还有其他实现方式如利用静态内部类等,其中最好的方式是:
//实现方式4、枚举(Effective Java中讲解这是单例的最佳实现,可以防止反射,反序列化等构建对象)
public enum Singleton {
INSTANCE;
}