单例模式的特点:
- 单例类只能有一个实例
- 单例类必须自己创建自己的唯一实例
- 单例类必须给所有其他对象提供这一对象实例
饿汉式-------以空间换取时间
public class Student {
//提供私有静态该类类型属性,赋值
private static Student s = new Student();
//构造方法私有
private Student(){
}
//对外提供一个静态的方法
public static Student getInstance(){
return s;
}
}
懒汉是-------以时间换取空间
public class Student {
//构造方法私有
private Student(){}
//提供私有静态该类类型属性
private static Student s;
//对外提供一个静态的方法
public static Student getIN(){
//并不是直接创建对象,而是判断,然后再根据情况是否创建对象
if(s !=null){
return s;
}
s =new Student();
return s;
}
}
public static void main(String[] args) {
Student s1 =Student.getInstance();
Student s2 =Student.getInstance();
System.out.println(s1);
System.out.println(s2);
}
结果:com.zhiyou100.controller.Student@5ce65a89
com.zhiyou100.controller.Student@5ce65a89
设计模式参考该接:https://blog.csdn.net/jason0539/article/details/44956775