1.单例模式(Singleton),保证一个类仅有一个实例,并提供一个访问它的全局访问点。
希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。
饿汉式单例:
/**
* 饿汉式单例
*
* @author Administrator
*
*/
public class Student {
private Student() {
}
private static Student s = new Student();
public static Student getStudent() {
return s;
}
}
懒汉式:
/**
* 懒汉式单例
* @author Administrator
*
*/
public class Teacher {
private Teacher() {
}
private static Teacher t = null;
//synchronized同步,线程安全
public synchronized static Teacher getTeacher() {
if (t == null) {
t = new Teacher();
}
return t;
}
}
开发中一般采用饿汉式,原因,多线程安全问题。
面试会面懒汉式,主要以下几个问题:
1、延迟加载思想。2、线程安全问题。
Runtime类就是单例模式的应用。