1.饿汉式
class SingIeton(){
private SingIeton(){}
private final static SingIeton instance=new SingIeton();
public static SingIeton getInstance(){
return instance;
}
}
2.饿汉式(静态代码块)
class SingIeton(){
private SingIeton(){}
private static SingIeton instance;
stati{
instance=new SingIeton();
}
public static SingIeton getInstance(){
return instance;
}
}
3.懒汉式(线程不安全)
class SingIeton(){
private SingIeton(){}
private static SingIeton instance;
public static SingIeton getInstance(){
if(instance!=null){
instance=new SingIeton();
}
return instance;
}
}
4.懒汉式(线程安全)
class SingIeton(){
private SingIeton(){}
private static SingIeton instance;
public static synchronized SingIeton getInstance(){
if(instance!=null){
instance=new SingIeton();
}
return instance;
}
}
5.懒汉式(线程安全) 同步代码块
6.双重检查
class SingIeton{
private static volatile SingIeton instance;
private SingIeton(){}
private static synchronized SingIeton getInstance(){
if(instance==null)
synchronized(SingIeton.class){
if(instance==null)
instance=new SingIeton();
}
}
return instance;
}
7.静态内部类
class Singleton {
private static volatile Singleton instance;
//构造器私有化
private Singleton() {}
//写一个静态内部类,该类中有一个静态属性 Singleton
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
//提供一个静态的公有方法,直接返回 SingletonInstance.INSTANCE
public static synchronized Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
8.枚举
enum Singleton {
INSTANCE; //属性
public void sayOK() {
}
}