java单例设计模式

什么是单例设计模式

单例即只有一个实例,该模式的作用是保证程序中某个类的对象只有一个。

单例模式分为懒汉式和饿汉式。

懒汉式

class Student{ static Student st; private Student(){} public static Student getInstance(){ //引用数据类型属性在内存中的默认值为null //如果值为null 只创建一次对象 if(st==null){ st = new Student(); } return st; } } public class Test1 { public static void main(String[] args) { // 利用hascode 相等 是单例 Student tes1 = Student.getInstance(); System.out.println(tes1.hashCode()); Student tes2 = Student.getInstance(); System.out.println(tes2.hashCode()); } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpyjxy.html