// 饿汉模式
private SimpleTest(){
}
private static SimpleTest instance = new SimpleTest();
public static SimpleTest getinstance(){
return instance;
}
}
public class SimpleTest1 {
// 懒汉模式
private SimpleTest1(){
}
private static SimpleTest1 instance;
public static SimpleTest1 getInstance(){
if(instance == null){
instance = new SimpleTest1();
}
return instance;
}
}
//线程安全
private volatile static SimpleTest3 singleton;
private SimpleTest3(){
}
public static SimpleTest3 getInstance() {
if (singleton== null) {
synchronized (SimpleTest3.class) {
if (singleton== null) {
singleton= new SimpleTest3();
}
}
}
return singleton;
}
public class SimpleTest4 {
// 静态内部类单例模式
private SimpleTest4(){
}
public static SimpleTest4 getInstance(){
return SingletonHolder.sInstance;
}
private static class SingletonHolder {
private static final SimpleTest4 sInstance = new SimpleTest4();
}
}
//枚举单例的优点就是简单,但是大部分应用开发很少用枚举,可读性并不是很高,不建议用。
public enum SimpleTest5 {
INSTANCE;
public void doSomeThing() {
}
}