单例模式
一、
二、
1. 饿汉式:类初始化时,会立即加载该对象,线程天生安全,调用效率高。
2. 懒汉式: 类初始化时,不会初始化该对象,真正需要使用的时候才会创建该对象,具备懒加载功能
public class TestModel {
public static void main(String[] args) {
SingletonDemo01 instance1 = SingletonDemo01.getInstance();
SingletonDemo01 instance2 = SingletonDemo01.getInstance();
System.out.println(instance1 == instance2);
SingletonDemo02 instance3 = SingletonDemo02.getInstance();
SingletonDemo02 instance4 = SingletonDemo02.getInstance();
System.out.println(instance3 == instance4);
}
}
// 饿汉式
class SingletonDemo01{
// 类初始化时,会立即加载该对象,线程天生安全,调用效率高
private static SingletonDemo01 singletonDemo01 = new SingletonDemo01();
private SingletonDemo01(){
System.out.println("SingletonDemo01初始化");
}
public static SingletonDemo01 getInstance(){
System.out.println("getInstance");
return singletonDemo01;
}
}
// 懒汉式
class SingletonDemo02 {
//类初始化时,不会初始化该对象,真正需要使用的时候才会创建该对象。
private static SingletonDemo02 singletonDemo02;
private SingletonDemo02(){
}
public synchronized static SingletonDemo02 getInstance(){
if(singletonDemo02 == null){
singletonDemo02 = new SingletonDemo02();
}
return singletonDemo02;
}
}