单例模式
- 应用场景:
- 有些对象只需要一个配置文件、工具类、线程池、缓存、日志对象等。
- 如果创造多个实例就会导致许多问题,比如占用过多的资源、不一致的结果等。
- 作用:保证整个应用程序中某个实例有且仅有一个。
- 两种类型: 饿汉模式和懒汉模式。
- 代码示例
public class HungrySingleton {
private HungrySingleton() {
}
private static HungrySingleton hungrySingleton = new HungrySingleton();
public static HungrySingleton getInstance() {
return hungrySingleton;
}
}
public class HungrySingleton {
private HungrySingleton() {
}
private static class Holder{
private static HungrySingleton hungrySingleton = new HungrySingleton();
}
public static HungrySingleton getInstance() {
return Holder.hungrySingleton;
}
}
public class LazySingleton {
private LazySingleton() {
}
private static LazySingleton lazySingleton;
public static LazySingleton getInstance() {
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
public class LazySingleton {
private LazySingleton() {
}
private static LazySingleton lazySingleton;
public synchronized static LazySingleton getInstance() {
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
public class LazySingleton {
private LazySingleton() {
}
private static LazySingleton lazySingleton;
public static LazySingleton getInstance() {
synchronized(LazySingleton.class){
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
}
return lazySingleton;
}
}
public class LazySingleton {
private LazySingleton() {
}
private static LazySingleton lazySingleton;
public static LazySingleton getInstance() {
if(null == lazySingleton)
synchronized(LazySingleton.class){
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
return lazySingleton;
}
}
public class LazySingleton {
private LazySingleton() {
}
private volatile static LazySingleton lazySingleton;
public static LazySingleton getInstance() {
if(null == lazySingleton)
synchronized(LazySingleton.class){
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
return lazySingleton;
}
}