package singletonmethod;
/**
* 懒汉模式
* @author Bingo.Ge
* @date 2020年5月7日
*/
public class LazySingleton {
private static LazySingleton instance;
// 不能new实例
private LazySingleton() {
}
public static LazySingleton getInstance() {
if(instance == null) {
// 如果instance==null才需要new实例,synchronized防止多线程并发
synchronized (LazySingleton.class) {
// 再判断一次防止多线程同时进入到第一个if中
if(instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}
/**
*
*/
package singletonmethod;
/**
* 饿汉模式
* @author Bingo.Ge
* @date 2020年5月7日
*/
public class HungrySingleton {
// 只会在类初始化时加载一次
private static HungrySingleton instance = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return instance;
}
}