实现单例模式的方法除了常见的饿汉式懒汉式,还可以通过静态内部类,枚举等方式来实现。
饿汉式:
public class SingletonHungry01 {
private SingletonHungry01() {
}
private static SingletonHungry01 singleton = new SingletonHungry01();
public static SingletonHungry01 getInstance(){
return singleton;
}
}
懒汉式:
public class SingletonLazy02 {
private SingletonLazy02() {}
private static SingletonLazy02 singleton = null;
public static SingletonLazy02 getInstance(){
if (singleton==null) {
singleton = new SingletonLazy02();
}
return singleton;
}
}
静态类部类:
public class SingletonClass {
private SingletonClass(){}
static class innerClass{
private static SingletonClass singletonClass = new SingletonClass();
}
public static SingletonClass getNewInstence(){
return innerClass.singletonClass;
}
}
枚举的方式:枚举实现单例(线程安全,天然就是单例的,能避免反射和反序列化带来的问题,但是不能懒加载)。
public enum SingletonEnum {
singleton;
public void single(){
System.out.println("I'm the east of the david");
}
}