java单例模式之饿汉模式与懒汉模式
单例模式的特点:保证整个应用程序中某个实例有且只有一个
1、饿汉模式
特点:类加载时就创建了对象,
加载类时比较慢,但运行时获取对象的速度比较快,线程安全
public class Singleton {
//1.将构造方法私有化,不允许外部直接创建对象
private Singleton(){
}
//2.创建类的唯一实例,使用private static修饰
private static Singleton instance=new Singleton();
//3.提供一个用于获取实例的方法,使用public static修饰
public static Singleton getInstance(){
return instance;
}
}
2、懒汉模式
特点:类在运行时才创建对象
加载类时比较快,但运行时获取对象的速度比较慢,线程不安全
public class Singleton2 {
//1.将构造方式私有化,不允许外边直接创建对象
private Singleton2(){
}
//2.声明类的唯一实例,使用private static修饰
private static Singleton2 instance;
//3.提供一个用于获取实例的方法,使用public static修饰
public static Singleton2 getInstance(){
if(instance==null){
instance=new Singleton2();
}
return instance;
}
}