饿汉式
特点:线程安全,调用效率高,但是不能延时加载
public class SingletonDemo01{
private static SingletonDemo1 instance = new SingletonDemo1();
private SingletonDemo1(){}
public static SingletonDemo1 getInstance(){
return instance;
}
}
懒汉式
特点:线程安全,调用效率不高,但是能延时加载
public class SingletonDemo2{
//类初始化时,不初始化这个对象(延时加载,真正用的时候再加载)
private static SingletonDemo2 instance;
//构造器私有化
private SingletonDemo2(){}
//方法同步,调用效率低
public static synchronized SingletonDemo2 getInstance(){
if(instance == null){
instance = new SingletonDemo2();
}
return instance;
}
}
标签:23,private,public,instance,static,单例,设计模式,SingletonDemo1,SingletonDemo2 From: https://www.cnblogs.com/houhuilinblogs/p/18041375