懒汉模式在序列化机制中的实例
import java.io.*;
public class LazyTest {
public static void main(String[] args) {
Lazy lazy = Lazy.getInstance();
try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("test"));){
try {
Lazy lazy1 = (Lazy) objectInputStream.readObject();
System.out.println(lazy1==lazy);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Lazy implements Serializable {
private static final long serialVersionUID = -3372123889599862014L;
private volatile static Lazy instance;
private Lazy() {
}
public static Lazy getInstance() {
if (null == instance) {
synchronized (Lazy.class) {
if (null == instance) {
instance = new Lazy();
}
}
}
return instance;
}
Object writeReplace() throws ObjectStreamException{
return getInstance();
}
}
懒汉模式在内部类中的实例
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class InnerClassTest {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
System.out.println(Inner.getInstance());
Constructor<Inner> declaredConstructor = Inner.class.getDeclaredConstructor();
declaredConstructor.setAccessible(true);
Inner inner = declaredConstructor.newInstance();
Inner instance = Inner.getInstance();
System.out.println(inner==instance);
}
}
class Inner {
public static String name = "fan !";
static{
System.out.println("InnerClass !");
}
private static class SingHolder {
static{
System.out.println("SingHolder !");
}
private static Inner instance = new Inner();
}
private Inner() {
if (SingHolder.instance != null) {
throw new RuntimeException("单例不允许多个实例!");
}
}
public static Inner getInstance() {
return SingHolder.instance;
}
}
懒汉模式在枚举中的实例
public class EnumSingTest {
public static void main(String[] args) {
EnumSing instance = EnumSing.INSTANCE;
instance.doBiz();
EnumSing instance1 = EnumSing.INSTANCE;
instance1.doBiz();
}
}
enum EnumSing {
INSTANCE;
public void doBiz() {
System.out.println(hashCode());
}
}
饿汉模式
public class HungryTest {
public static void main(String[] args) {
Class<Hungry> hungryClass = Hungry.class;
Hungry.print();
}
}
class Hungry {
public static String name = "fan";
static {
System.out.println("Hungry !");
}
private static Hungry instance = new Hungry();
private Hungry() {
}
public static Hungry getInstance() {
return instance;
}
public static void print() {
System.out.println("fanzongshen !");
}
}