对象在new的时候就会创建一个新的地址,所以需要将实例先提前初始化为静态的,在调用时直接用类调用,便不需要new出来了
饿汉式是线程安全的
懒汉式是非线程安全的
1 package object.singleton; 2 3 public class Student { 4 //饿汉式 5 private static Student student=new Student();//初始化一个实例 6 7 public static Student getInstance(){ 8 9 return student; 10 11 } 12 13 }
结果:
object.singleton.Student@15db9742
object.singleton.Student@15db9742
1 package object.singleton; 2 3 public class Student { 4 //懒汉式 5 private static Student student=null;//初始化一个实例 6 7 public static Student getInstance(){ 8 if(student==null){ 9 student=new Student(); 10 } 11 return student; 12 13 } 14 15 }
结果:
object.singleton.Student@15db9742
object.singleton.Student@15db9742
1 package object.singleton; 2 //懒汉式和饿汉式的测试 3 public class Singleton { 4 public static void main(String[] args) { 5 Student stu1=Student.getInstance(); 6 Student stu2=Student.getInstance(); 7 System.out.println(stu1); 8 System.out.println(stu2); 9 10 } 11 }