饿汉:加载类的时候对象就被创建出来,因此虚拟机会保证了线程安全。
/** 懒汉式*/
class SingletonOne {
private static SingletonOne singleton = new SingletonOne();
public static SingletonOne getSingleton(){
return singleton;
}
private SingletonOne(){}
}
```
双重校验锁:不再啰嗦啦。
```
/** 双重校验锁*/
class SingletonTwo{
private SingletonTwo(){}
private volatile static SingletonTwo singletonTwo = null;
public static SingletonTwo getSingletonTwo(){
if (singletonTwo == null){
synchronized (SingletonTwo.class){
if (singletonTwo == null){
singletonTwo = new SingletonTwo();
}
}
}
return singletonTwo;
}
}
```
枚举实现:很优雅,但是结构很奇怪。
```
/** enum*/
enum SingletonThree{
/** Instance enum*/
INSTANCE;
public void dosomething(){
}
}
```
```
/** 静态内部类*/
class SingletonFour{
private SingletonFour(){}
private static class SingletonHandler{
private static final SingletonFour INSTANCE= new SingletonFour();
}
public static SingletonFour getSingletonFour(){
return SingletonHandler.INSTANCE;
}
}
```