《Effective Java》读书笔记:Item3实现单例的几种方式
程序员文章站
2022-03-19 16:01:47
方法一:public fieldpublic class ExampleSingleton{ public static final ExampleSingleton INSTANCE = new ExampleSingleton(); private ExampleSingleton(){ ... } public void doSomething(){ ... }}方法二:static factorypublic class ExampleSingleton{...
方法一:public field
public class ExampleSingleton{
public static final ExampleSingleton INSTANCE = new ExampleSingleton();
private ExampleSingleton(){ ... }
public void doSomething(){ ... }
}
方法二:static factory
public class ExampleSingleton{
private static final ExampleSingleton INSTANCE = new ExampleSingleton();
private ExampleSingleton(){ ... }
public static ExampleSingleton getInstance(){
return INSTANCE;
}
public void doSomething(){ ... }
}
前者优点是简单;后者优点是灵活,如果想去除单例模式,不必修改 getInstance() 接口。共同缺点:反射(见Item65)和反序列化(Item89)会创建不止一个对象,破坏单例。
方法三:利用枚举(推荐)
public enum ExampleSingleton{
INSTANCE;
public void doSomething(){ ... }
}
优点:反射和反序列化依然保证单例,原理:根据《Thinking in Java》第12章,编译器会保证一旦enum定义结束,不允许再使用构造器创建实例。
最后,关于方法二中线程同步的讨论,书中没有涉及,可参考:https://www.cnblogs.com/happy4java/p/11206105.html
本文地址:https://blog.csdn.net/littelsnail/article/details/111957685