《Effective Java》作者推荐枚举实现单例类
---享有特权的客户端可以借助AccessibleObject.setAccessible方法,通过反射机制调用私有构造器。如果需要低于这种攻击,可以修改构造器,让它在被要求创建第二个实例的时候抛出异常
好处如下:
1、实现简单
2、防反序列化(readObject生成新的单例)
3、避免反射攻击
代码实现:(枚举单例类 共享变量)
import java.util.Arrays;
import java.util.List;
public enum EnumSingleton
{
INSTANCE;
// cache
private List<String> lstStr;
/**
* get str cache
*/
public synchronized List<String> getStrCache()
{
if (null == this.lstStr)
{
System.out.println("init----------");
this.lstStr = Arrays.asList(new String[]{"a","b"});
}
return this.lstStr;
}
}
import java.util.List;
public class TestEnumSingleton
{
public static void main(String[] args)
{
new Thread(new Runnable(){
@Override
public void run()
{
List<String> ret = EnumSingleton.INSTANCE.getStrCache();
System.out.println(ret.toString());
}
}).start();
new Thread(new Runnable(){
@Override
public void run()
{
List<String> ret = EnumSingleton.INSTANCE.getStrCache();
System.out.println(ret.toString());
}
}).start();
}
}
输出:
init----------
[a, b]
[a, b]
参考:
为什么要用枚举单例:https://www.cnblogs.com/chiclee/p/9097772.html
饿汉式、静态内部类写法参考:http://www.importnew.com/18872.html