单例模式五种方式
饿汉式
public class Singleton{
private static final Singleton instance = new Singleton();
private Singleton() { // 防止暴力反射
if (instance != null) {
throw new RunTimeException("单例对象不能重复被创建");
}
System.out.println("new Singleton...");
};
public static Singleton getInstance() {
return instance;
}
public Object readResolve() { // 防止反序列化破坏单例
return instance;
}
}
饿汉枚举
public Enum Singleton{
INSTANCE;
}
懒汉式
public class Singleton {
private static final Singleton instance = null;
private Singleton(){}
public static synchronized Singleton getInstance() {
if (instance != null) {
instance = new Singleton();
}
return instance;
}
}
双检索懒汉
public class Singleton {
private static final volatile Singleton instance = null;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
synchronized(Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
内部类懒汉式
public class Singleton {
private Singleton(){};
private static class Holder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance () {
return Holder.instance;
}
}
作者:万能包哥 出处:http://www.cnblogs.com/mybloger/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |