单例模式保证一个类只有一个实例。
单例
有些对象占用重要的系统资源,必须限制这些实例的创建或始终使用一个公用的实例。单例模式能保证一个类只有一个实例。
懒汉式单例类
在第一次调用的时候实例化自己。
通过限定构造函数为private避免类在外部被实例化,singleton的唯一实例只能通过getInstance( )方法访问到。
public class LazySingleton {
private LazySingleton() { }
private static LazySingleton lazySingleton = null;
public static LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
这种方式是线程不安全的,并发环境下很可能出现多个singleton实例,可以在getInstance加上同步。
public class LazySingleton {
private LazySingleton() { }
private static LazySingleton lazySingleton = null;
public static synchronized LazySingleton getInstance() {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
在 new Singleton()时仍会出现并发问题,可以用双重锁。
public class LazySingleton {
private LazySingleton() { }
private static LazySingleton lazySingleton = null;
public static synchronized LazySingleton getInstance() {
if (lazySingleton == null) {
synchronized (LazySingleton.class) {
if (lazySingleton == null) {
lazySingleton = new LazySingleton();
}
}
}
return lazySingleton;
}
}
饿汉式单例类
饿汉式在类加载时就已经创建好了一个静态对象供系统使用,所以是天生线程安全的。但不论是否会使用这个单例,都会占用一定的内存,但相应的第一次调用时速度更快。
public class EagerSingleton {
private EagerSingleton() { }
private static final EagerSingleton eagerSingleton = new EagerSingleton();
public static EagerSingleton getInstance() {
return eagerSingleton;
}
}