利用枚举实现单例模式
enum Singleton8{
INSTANCE;
public void sayOk(){
System.out.println("ok~");
}
}
借助jdk1.5新加的枚举,可以避免多线程问题,还可以防止反序列化重新创建新的对象。可以使用此种方法。
单例模式在JDK源码中的体现
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
在JDK中的RUNTIME对象就是利用了单例模式中的饿汉式的静态变量的方式实现的。
单例模式的注意事项和细节说明
- 单例模式保证了系统内存中只存在一个对象,节省了系统资源,对于一些需要频繁创建销毁的对象,使用单例模式可以提高系统性能。
- 当想实例化一个单例对象的时候,必须要记住使用相应的获取对象的方法,比如对象的getInstance()方法,而不是使用new
- 单例模式的使用场景:需要频繁的创建和销毁的对象,创建对象会消耗过多的时间和资源(重量级对象),但又经常用到的对象,工具类对象,频繁访问数据库或文件的对象(比如数据源,session工厂等)