第一种、懒汉式(在需要实例对象的时候提供)
/**
* 懒汉式,提供一个getInstance方法,在需要实例时,才调用
* (线程不安全,可以在getInstance上加synchronized保证线程安全,但是性能不高)
* @author wb
*
*/
public class Singleton {
//只提供一个无参构造方法,并且私有化
private Singleton(){};
//私有一个实例
private static Singleton instance;
//对外提供一个getInstance方法,获取实例
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
第二种、 饿汉式(不管你需不需要,一开始,就创建一个实例对象)
/**
* 饿汉式,不管你需不需要,一开始,就创建一个实例对象
(线程不安全,可以在getInstance上加synchronized保证线程安全,但是性能不高) * @author wb
*
*/
public class Singleton {
//先私有化无参构造方法
private Singleton (){};
private static Singleton instance=null;
static {
instance =new Singleton();
}
public static Singleton getInstance(){
return instance;
}
}
第三种、静态内部类
/**
* 静态内部类
* 保证在调用getInstance方法的时候,再去实例化一个对象,体现了延时加载优点
* @author wb
*
*/
public class Singleton {
//先私有化无参构造方法
private Singleton (){};
private static class SingletonHander{
//final化
private final static Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return SingletonHander.INSTANCE;
}
}
第四种、双重校验锁
/**
* 双重校验锁
* @author wb
*
*/
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
/**
* 双重校验锁
* @author wb
*
*/
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {
}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}