模式定义
确保一个类最多只有一个实例,并提供一个全局访问点。
单例模式分为饿汉式和懒汉式。
懒汉式单例模式:在类加载时不初始化。
饿汉式单例模式:在类加载时就完成了初始化,所以类加载比较慢,但获取对象的速度快。
饿汉式-线程安全
/**
* 饿汉式单例模式(线程安全)
*/
public class Singleton {
//static单例变量
private static Singleton singleton = new Singleton();
//私有的构造方法
private Singleton() {
}
//静态方法为调用者提供单例对象
public static Singleton getInstance() {
return singleton;
}
}
懒汉式-线程不安全
/**
* 懒汉式(线程不安全)
*/
public class Singleton2 {
private static Singleton2 instance = null;
private Singleton2() {
}
public static Singleton2 getInstance() {
if (instance == null) {
instance = new Singleton2();
}
return instance;
}
}
懒汉式-线程安全
/**
* 懒汉式(线程安全)
*/
public class Singleton3 {