常见的单例模式由5种
1.饿汉模式
package day01.pattern;
import java.io.Serializable;
class Singleton1 implements Serializable {
private static final Singleton1 INSTANCE = new Singleton1();
private Singleton1() {
if(INSTANCE!=null){
throw new RuntimeException("单例对象不能重复创建");
}
}
public Object readResolve(){
return INSTANCE;
}
public static Singleton1 getINSTANCE() {
return INSTANCE;
}
}
2.枚举饿汉模式
package day01.pattern;
public enum Singleton2 {
INSTANCE;
private Singleton2(){
System.out.println("privet Singleton2()");
}
@Override
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
public static Singleton2 getINSTANCE() {
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod");
}
}
3.懒汉模式
package day01.pattern;
import java.io.Serializable;
class Singleton3 implements Serializable {
private static Singleton3 INSTANCE = null;
private Singleton3() {
System.out.println("private singleton3()");
}
public static synchronized Singleton3 getINSTANCE() {
if(INSTANCE == null) {
INSTANCE = new Singleton3();
}
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod");
}
}
4.懒汉模式 DCL (双检锁)
package day01.pattern;
import java.io.Serializable;
class Singleton4 implements Serializable {
private volatile static Singleton4 INSTANCE = null;
private Singleton4() {
System.out.println("private singleton4()");
}
public static Singleton4 getINSTANCE() {
if(INSTANCE == null) {
synchronized (Singleton4.class) {
if(INSTANCE == null) {
INSTANCE = new Singleton4();
}
}
}
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod");
}
}
5.内部类懒汉式
package day01.pattern;
import java.io.Serializable;
class Singleton5 implements Serializable {
private static class Holder{
static Singleton5 INSTANCE = new Singleton5();
}
private Singleton5() {
System.out.println("private singleton5()");
}
public static Singleton5 getINSTANCE() {
return Holder.INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod");
}
}
JDK中有哪些地方体现了单例模式
Runtime.class