欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

单例模式-Singleton的几种方式

程序员文章站 2022-03-07 18:07:12
...

实例证明用枚举方式实现单例是最佳方式;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;

public class Singleton {
	public static void main(String[] args) throws  Exception {
		Class<?> clazz = Singleton3.class;
		Constructor[] c = clazz.getDeclaredConstructors();
		if(c.length>0) {
			/**更改默认控制,使私有类型可以访问**/
			c[0].setAccessible(true);
			Object obj = c[0].newInstance(null);
			Object obj2 = Singleton3.INSTANCE;
			System.out.println(obj == obj2);//false
		}
		/**通过序列化和反序列化生成不同的对象**/
		Singleton2 sing = Singleton2.INSTANCE;
		seriObj(sing);
		Class<?> clazz2 = Singleton2.class;
		Constructor[] c2 = clazz2.getDeclaredConstructors();
		if(c2.length > 0) {
			c2[0].setAccessible(true);
			//Object obj3 = c2[0].newInstance(null);
		}
		Class<?> clazz4 = Singleton4.class;
		Constructor[] c4 = clazz4.getDeclaredConstructors();
		if(c4.length > 0) {
			c4[0].setAccessible(true);
			/**运行时异常,提示不能反射创建枚举类型**/
			//Object obj6 = c4[0].newInstance(null);
		}
		/**序列化枚举,反序列化得到的是同一个对象**/
		seriObj(Singleton4.SINGLETON);//true
	}
	private static void seriObj (Object obj) throws Exception, IOException {
		cleanFile("object.txt");
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("object.txt"));
		out.writeObject(obj);
		out.close();
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("object.txt"));
		Object sing2 = in.readObject();
		in.close();
		System.out.println(obj.getClass().getSimpleName()+":"+(obj == sing2));//false
	}
	private static void cleanFile(String path) {
		File file = new File(path);
		if(file.exists()) {
			if(file.isFile()) {
				/**删除文件**/
				file.delete();
			}
		}
	}
}
class Singleton3 {
	public static final Singleton3 INSTANCE = new Singleton3();
	private Singleton3() {}
}
class Singleton2 implements Serializable{
	public static final Singleton2 INSTANCE = new Singleton2();
	private Singleton2() {
		/**可以通过抛出异常的方式阻止创建对象**/
		if(null !=INSTANCE) {
			throw new RuntimeException("系统不能同时存在多个实例!");
		}
	}
}
enum Singleton4 {
	SINGLETON,
	Singleton4() {
		
	}
}



转载于:https://my.oschina.net/u/782865/blog/203200