一、单例模式
单例模式是指在内存中只会创建且仅创建一次对象的设计模式。在程序中多次使用同一个对象且作用相同时,为了防止频繁地创建对象使得内存飙升,单例模式可以让程序仅在内存中创建一个对象,让所有需要调用的地方都共享这一单例对象。
二、懒汉式和饿汉式
无论是饿汉还是懒汉单例模式都需要我们将构造函数私有化,使得对象只会单次创建。
懒汉单例模式:
public class Student {
public String name;
private static final Student student = new Student();
//私有化构造方法
private Student(){
}
public static Student getStudent(){
return student;
}
}
懒汉单例模式是在程序运行开始加载类时就会创建这个对象,这种写法比较简单,就是在类装载的时候就完成实例化。避免了线程同步问题。
饿汉单例模式:
public class UNStudent {
public String name;
private static UNStudent unstudent;
//私有化构造方法
private UNStudent(){
}
//懒汉模式(双重检查)
public static UNStudent getStudent(){
if (unstudent == null) {
synchronized (UNStudent.class) {
if (unstudent == null) {
unstudent = new UNStudent();
}
}
}
return unstudent;
}
}
饿汉单例模式在使用时才会对对象进行创建,在使用饿汉单例模式得到对象时我们需要进行双重验证,提高程序的运行效率,防止因为上锁导致程序效率降低的问题。在锁的监视器方面,类是用来抽象对象,在Java中有Class用来抽象类,所以我们使用类名.class作为synchronized的监视器。