- 单例模式的五种实现方式。
- 了解JDK中哪些地方体现了单例模式。
- Runtime类(饿汉式)、System类(双检锁-懒汉式)、Collections工具类。可到idea中查看源码。
饿汉式
package com.jie.singleton;
import java.io.Serializable;
public class Singleton1 implements Serializable {
private Singleton1(){
if (INSTANCE!=null){
throw new RuntimeException("单例模式不能重复创建对象");
}
System.out.println("private Singleton1()...");
}
private static final Singleton1 INSTANCE=new Singleton1();
public static Singleton1 getInstance(){
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod()...");
}
public Object readResolve(){
return INSTANCE;
}
}
package com.jie.singleton;
public enum Singleton2 {
INSTANCE;
Singleton2() {
System.out.println("Singleton2 ...");
}
public static Singleton2 getInstance() {
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod()...");
}
@Override
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
}
懒汉式
package com.jie.singleton;
public class Singleton3 {
private static Singleton3 INSTANCE=null;
private Singleton3(){
if (INSTANCE!=null){
throw new RuntimeException("单例模式不能重复创建对象");
}
System.out.println("private Singleton1()...");
}
public static synchronized Singleton3 getInstance(){
if (INSTANCE==null){
INSTANCE=new Singleton3();
}
return INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod()...");
}
}
package com.jie.singleton;
public class Singleton4 {
public static volatile 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()...");
}
}
package com.jie.singleton;
public class Singleton5 {
private Singleton5(){
System.out.println("private Singleton5()...");
}
private static class Holder{
static Singleton5 INSTANCE=new Singleton5();
}
public static Singleton5 getInstance(){
return Holder.INSTANCE;
}
public static void otherMethod(){
System.out.println("otherMethod()...");
}
}
参考
单例模式详解