单例模式
饿汉模式:
public class HungrySingleton {
//创建一个私有对象
private static HungrySingleton instance = new HungrySingleton();
//无参构造
private HungrySingleton() {}
//定义方法,返回值是HungrySingleton类型
//调用此方法,返回上面创建好的私有对象instance
public static HungrySingleton getInstance() {
return instance;
}
}
懒汉模式:
public class LazySingleton {
//创建一个私有对象
private static LazySingleton instance = null;
//无参构造
private LazySingleton() {}
//定义方法,返回值是LazySingleton类型
public static synchronized LazySingleton getInstance() {
//构造方法私有,其他地方调用不了,只有当第一次调用此方法时,对象才是初始值空
if(instance == null) {
try {
//睡眠
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//对象instance赋值,在if代码块里,第一次赋值后,不可能再通过if判断条件
instance = new LazySingleton();
}
//返回对象instance
return instance;
}
}
测试类
public class Test {
public static void main(String[] args) {
// HungrySingleton hs = new HungrySingleton();
HungrySingleton hs1 = HungrySingleton.getInstance();
HungrySingleton hs2 = HungrySingleton.getInstance();
System.out.println(hs1 == hs2);
LazySingleton ls1 = LazySingleton.getInstance();
LazySingleton ls2 = LazySingleton.getInstance();
System.out.println(ls1 == ls2);
}
}