单例模式:在内存中创建一个对象
饿汉式:不会出问题单例模式
前提条件:
1)当前类是一个具体类
2)类的无参构造方法私有化
3)在成员变量位置:提供一个当前类的静态实例变量
4)提供静态功能,当前这个方法返回值是当前类本身
jdk提供的Runtime这个类就是饿汉式:类一加载就创建当前类对象
public class Student{ private static Student s=new Student(); private Student(){} public static Student getStudent(){ return s; } }
测试类:
public class SingleTest { public static void main(String[] args) throws IOException { Student s1= new Student(); Student s2= new Student(); System.out.println(s1==s2);//值为true } }
懒汉式:可能出现问题的单例模式
前提条件:
1)当前类是一个具体类
2)无参构造方法私有化
3)当前成员变量位置:仅仅声明一个当前类型静态变量,没有创建对象
4)对外提供静态的公共方法,返回值是当前类本身,但是里面需要用的时候才创建对象
public class Teacher {//具体类 //成员变量:私有的静态变量t:类型 Teacher private static Teacher t = null ; //无参构造私有化:外界不能去new private Teacher(){} //对外提供公共静态方法,返回值是当前类本身 //线程t1操作这个类,同时t2,t3 /*public static Teacher getTeacher(){ //加入同步锁 synchronized (Teacher.class){ //静态方法的锁对象:跟类有关系 类的字节码文件 类名.class //判断 if(t==null){ //没有对象,这个时候才去new 对象 t = new Teacher() ; } return t ; } }*/ //如果一个方法一进来就是一个同步代码块----优化为同步方法 public synchronized static Teacher getTeacher(){ //静态同步方法 //加入同步锁 //静态方法的锁对象:跟类有关系 类的字节码文件 类名.class //判断 if(t==null){ //没有对象,这个时候才去new 对象 t = new Teacher() ; } return t ; } }
测试类:
public class TeacherDemo { public static void main(String[] args) { Teacher t1 = Teacher.getTeacher(); Teacher t2 = Teacher.getTeacher(); System.out.println(t1==t2);//值为true } }