单例模式实现;
灭霸所有单例模式,克隆、序列化、反射机制破坏7种单例模式;
枚举实现单例;
破坏单例模式测试代码
import java.io.Serializable; public class Singleton implements Cloneable, Serializable { private static volatile Singleton singleton; private Singleton() { if (null != singleton) { throw new RuntimeException(); } } public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } /** * 防止克隆攻击 * * @return * @throws CloneNotSupportedException */ @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } private Object readResolve() { return getInstance(); } }
public class Test1 { public static void main(String[] args) throws CloneNotSupportedException { Singleton singleton = Singleton.getInstance(); Singleton singleton1 = (Singleton) singleton.clone(); Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton.hashCode()); System.out.println(singleton1.hashCode()); System.out.println(singleton2.hashCode()); } }
public class Test2 { public static void main(String[] args) throws IOException, ClassNotFoundException { Singleton singleton = Singleton.getInstance(); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("d:\xttblog.obj")); oos.writeObject(singleton); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:\xttblog.obj"))); Singleton singleton1 = (Singleton) ois.readObject(); System.out.println(singleton.hashCode()); System.out.println(singleton1.hashCode()); System.out.println(singleton == singleton1); } }
public class Test3 { public static void main(String[] args) throws ReflectiveOperationException { Singleton singleton1 = Singleton.getInstance(); Class cls = Singleton.class; Constructor<Singleton> constructor = cls.getDeclaredConstructor(); constructor.setAccessible(true); Singleton singleton = constructor.newInstance(); System.out.println(singleton.hashCode()); System.out.println(singleton1.hashCode()); System.out.println(singleton == singleton1); } }