5种单例模式
1.饿汉式
class Singleton01{
private Singleton01(){/*构造方法要私有*/}
private static Singleton01 instance;
public static Singleton01 getInstance(){
//静态方法,获得实例
if(instance == null) {
//实例为空,则新建
instance = new Singleton01();
}
return instance;
}
}
2.懒汉式
方法是懒汉式,但是线程安全,但是性能不高。
class Singleton02{
paivate Singleton02(){/*私有构造方法*/}
private static Singleton02 instance;
Synchronized public static Singleton02 getInstance() {
if(instance == null) {
instance = new Singleton02();
}
return instance;
}
}
3.双重检查锁
双重检查锁是线程安全且效率较高的单例模式。并且使用了'volatile'关键字,禁止了指令重排。
class Singleton03{
private Singleton03(){/*私有构造方法*/}
private static Singleton03 instance;
public static volatile Singleton03(){
if(instance == null){
synochronized(Singleton.class){
if(instance == null){
instance = new Singleton03();
}
}
}
return instance;
}
}
4.饿汉式
饿汉式单例,类加载时就会构建对象,是线程安全的,但是存在资源的浪费
class Singleton04{
private Singleton04(){/*私有构造方法*/}
private static final Singleton04 instance = new Singleton04();
public static Singleton04 getInstance(){
return instance;
}
}
5.懒加载的饿汉式单例
懒加载的饿汉式单例。
class Singleton05{
private Singleton05(){/*私有构造方法*/}
static class Inner {
static Singleton05 instance = new Singleton05();
}
public static Singleton05 getInstance(){
return Inner.instance;
}
}